Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird output of simple expression in C, why?

Tags:

c++

c

turbo-c++

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?

like image 586
CocoCrisp Avatar asked Nov 27 '22 01:11

CocoCrisp


2 Answers

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.

like image 74
Sarima Avatar answered Dec 10 '22 15:12

Sarima


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.

like image 29
Bathsheba Avatar answered Dec 10 '22 15:12

Bathsheba