简体   繁体   中英

Unexpected output of C++ programm

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?

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?

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) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM