-5

I compiled the following code in turbo C compiler

void main()
{
  int i =400*400/400;

  if(i==400)
    cout<<"Filibusters";
  else
    cout<<"Sea ghirkins";
}

I expected the value of 'i' to be 400 and hence, the output should be Filibusters. However, the output I got is Sea Ghirkins. How is this possible?

HazemGomaa
  • 1,620
  • 2
  • 14
  • 21

2 Answers2

5

You are overflowing your int type: the behaviour on doing that is undefined.

The range of an int can be as small as -32767 to +32767. Check the value of sizeof int. If it's 2, then it will not be able to represent 400 * 400. You can also check the values of INT_MAX and INT_MIN.

Use a long instead, which must be at least 32 bits. And perhaps treat yourself to a new compiler this weekend?

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • The question was originally asked in turbo, and who doesn't know about c++14. I just wanted to know the output in turbo. – Shubham Bhatia Sep 16 '16 at 18:05
  • 1
    How in the great googly mooglies did C++14 get involved? This has been law since time immemorial. 400 * 400 likely equals 28928 (0x7100) due to 16 bit overflow. 28928 / 400 = 72. – user4581301 Sep 16 '16 at 18:18
  • @user4581301 If the size of integer is 4 bytes, then it would run as expected, the mention of c++14 is just to signify that the question was particularly asked to be compiled in turbo! – Shubham Bhatia Sep 16 '16 at 18:23
  • @ShubhamBhatia That is true if the size of `int` is 4 bytes. Bathsheba's point is a 4 byte `int` is not required by the standard, and this goes back past the origins of C++ and into it's roots in C. If you have Turbo C++ 3, designed for good ol' DOS and 16 bit Windows 3, the `int` only supports the bare minimum 16 bits. More recent TurboC++ used larger `int`s to keep pace with the native sizes of newer CPUs. If your code fails to produce 400, you likely have TurboC++ 3 or older. – user4581301 Sep 16 '16 at 18:32
3

Look at operator associativity: * and / are left-associative, that means your formula is calculated in this order: (400*400)/400

400*400=160000. Computer arithmetic is finite. You are using 16-bit compiler where int fits into 16 bits and can only hold values from range -32768 ... 32767 (why -32768?). 160000 obviously doesn't fit into that range and is trimmed (integer overflow occurs). Then you divide trimmed value by 400 and get something unexpected to you. Compilers of the past were quite straightforward so I would expect something like 72 to be stored into i.

The above means you can either use a bigger integer type - long which is able to store 160000 or change assiciativity manually using parenthesses: 400*(400/400).

Community
  • 1
  • 1
fukanchik
  • 2,811
  • 24
  • 29
  • 1
    "You are using 16-bit compiler" not necessarily: a 128 bit compiler can still have a 16 bit int. Also your lower limit of -32768 is only true for 2's complement int. Other than that, this answer is cute. – Bathsheba Sep 16 '16 at 16:52