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.
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 * 100000instead of10000 * 10000results 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