I am using TurboC++. I write the following expression which is not resulting in proper evaluation, am I missing some concept behind it?
int c=300*300/300;
printf("%d",c);
The output is
81
Why?
300*300 is 90000.
Assuming int is 16bit, you have overflowed.
The overflow wraps around, giving you: 24464
.
24465/300 = 81.55
Do not rely on this. It is undefined behavior.
The evaluation of 300 * 300 / 300 happens from left to right.
300 * 300 overflows a 16 bit signed integral type (an int
in Turbo C++ is 16 bit). As the computation will take place in signed arithmetic, the result is undefined.
What's happening is 300 * 300 is wrapping round to give you 24464. (24464 + 32768 + 32768 = 90000).
24464 / 300 is 81 in integer division.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With