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 开发者_StackOverflow中文版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.
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). E.g. (long)100000 * 100000
That's cause it first calculates it as an int, and only then casts it into a long variable.(so it first overflows as an integer and then becomes a long) the code should be
long int c = a*(long int)b;
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.
精彩评论