Why turbo c wraparound signed integer overflow every time though signed integer overflow is undefined?

109 views Asked by At

I have made signed overflow many times but each times turbo c wraparound. For example:

#include <stdio.h>

void main() {
  int i = 100000; 
  printf("%d", i);
  getch();
}

The output is -31072 which is the expected output if wraparound is done. In binary 100000(dec) is 11000011010100000 and last 16 bits are store which is 1000011010100000. In two complement representation 1000011010100000 is -31072.

1

There are 1 answers

0
2501 On BEST ANSWER

Your example doesn't have contain any signed overflows, so there is no undefined behavior.

(Assuming INT_MAX is less than 100000.)

The assignment:

int i=100000;

performs an implicit conversion from a type long, which is the type of the integer constant 100000, to type int. This result of conversion is implementation-defined1 (or an implementation-defined trap is signal).


1(Quoted from: ISO/IEC 9899:201x 6.3.1.3 Signed and unsigned integers 3)
Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.