Strange conclusion of a simple expression in C, why?

I am using TurboC ++. I am writing the following expression, which does not lead to a correct assessment, is there any missing concept behind it?

int c=300*300/300; printf("%d",c); 

Output signal

81

Why?

+4
source share
2 answers
 300*300 is 90000. 

Assuming int is 16 bits, you are overflowed.

Overflow wraps around, giving you: 24464 .

 24465/300 = 81.55 

Do not rely on this. This behavior is undefined.

+27
source

Evaluation 300 * 300/300 occurs from left to right.

300 * 300 overflows with a 16-bit signed int type ( int in Turbo C ++ is 16 bits). Since the calculation will be performed in signed arithmetic, the result is undefined .

What happens, 300 * 300 wraps around to give you 24464. (24464 + 32768 + 32768 = 90,000).

24464/300 - 81 in whole divisions.

+8
source

All Articles