CocoCrisp
CocoCrisp

Reputation: 815

Weird output of simple expression in C, why?

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?

Upvotes: 4

Views: 716

Answers (2)

Bathsheba
Bathsheba

Reputation: 234635

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.

Upvotes: 9

Sarima
Sarima

Reputation: 749

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.

Upvotes: 27

Related Questions