Why does the following code not give the desired answer?

Yesterday at the interview, the interviewer asked me a question:

Why does the following code not give the desired answer?

int a = 100000, b = 100000;

long int c = a * b ;

Language - C.

I told the interviewer that we would first calculate 100,000 * 100,000 as int (overflow) and just put it off until the end.

+3
source share
3 answers

I assume that the key will be an integer overflow , but with such low values, I do not see this happening.

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

The result of your calculation: 100,000,000

UPDATE:

With an updated question: 100000 * 100000instead, the 10000 * 10000result is 10,000,000,000, which will cause an overflow. Then this value is transmitted later.

, ( 64-). . (long)100000 * 100000

+5

int ( , )

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

100000*100000 10000000000 (10,000,000,000), , 32 int (2,147,483,647), .

a*b - int, a long int, a*b int, long int: , a*b , c. , a*b long int, long int:

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

, long int int ( 32 ): , , 32- , sizeof(int) == sizeof(long int) == 4.

c 64 , int64_t, , 64 .

+3

Source: https://habr.com/ru/post/1792782/


All Articles