简体   繁体   中英

Why doesn't the following code give the desired answer?

Yesterday on an interview the interviewer asked me a question:

Why doesn't the following code give the desired answer?

int a = 100000, b = 100000;

long int c = a * b ;

The language is C.

I've told the interviewer that we count first the 100,000 * 100,000 as an int(overflow) and just then cast it to long.

这是因为它首先将它计算为一个int,然后才将其转换为一个long变量。(因此它首先溢出为一个整数然后变成一个长整数)代码应该是

long int c = a*(long int)b;

I'm guessing the clue would be an integer overflow to occur, but with such low values, I don't see that happening.

Maximum (positive) value for int (usually 32bit) is: 2,147,483,647

The result of your calculation is: 100,000,000

UPDATE:

With your updated question: 100000 * 100000 instead of 10000 * 10000 results in 10,000,000,000 , which will cause an overflow to occur. This value is then cast to a long afterwards.

To prevent such an overflow the correct approach would be to cast one of the two values in the multiplication to a long (usually 64bit). Eg (long)100000 * 100000

100000*100000 is 10000000000 ( 10,000,000,000 ) which is greater than the maximum value a 32bit int can represent ( 2,147,483,647 ), thus it overflows .

a*b is still an int , it's not a long int , since the members of expression a*b are both of type int , thus they aren't converted to long int : this conversion will only happen after a*b has been evaluated, when the result is assigned c . If you want the result of a*b to be long int you need to convert at least one of the operands as long int :

long int c = (long int)a * (long int)b.

Moreover long int could be of the same size of int (it could be represented on 32 bits too): this is most likely to happen with 32 bit application where, usually, sizeof(int) == sizeof(long int) == 4 .

If you need c to be of 64 bits you should better use a variable like int64_t , that ensures you to be of 64 bits.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM