0
{
int i=1;
while(i<=32767)
{
printf("%d",i);
i=i+1;
}
}

It seems a simple program to print 1 to 32767 ...but when i reaches 32767 ...on incrementing value by 1.....it tries to go to 32768 which falls outside the range of integer and goes to other side that is -32768 .....due to which condition becomes true as i<=32767 i.e. -32768.....So it should work as indefinite loop. My Dev C++ Compiler prints only 1 to 32767....its not working as indefinite loop. Anybody

4

2 回答 2

10

Presumably the size of an integer on your platform is > 16 bits.

ISO/IEC 9899:201x states

minimum value for an object of type int

INT_MIN -32767 // −(215 − 1)

http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf

In fact, most C compilers these days, on most platforms, will have larger integers than 16 bits.

In C, an integer is guaranteed to be at least 16 bits. It is dangerous and non-portable to make an assumption that it is a specific size. Always check.

于 2012-10-08T18:02:03.997 回答
3

首先,您确定int您平台上的范围溢出32767吗?大多数现代平台使用 4 字节int,这意味着它的范围远大于-32768..+32767.

其次,有符号整数溢出会在 C 和 C++ 中产生未定义的行为。您期望32767变成-32768增量并且循环变得无限是完全没有根据的。该语言不保证这样的事情。您的程序可能会在发生溢出时简单地崩溃(某些编译器可以故意生成代码以确保程序在此类溢出时被中断)。

第三,一些现代编译器实现了所谓的严格溢出语义(GCC 就是一个例子)。由于有符号整数溢出会产生未定义的行为,因此编译器可以自由地以它认为合适的任何方式翻译代码。编译器可以将其转换为无条件无限循环。或者它可以将其转换为一些或多或少定义明确的终止循环。

于 2012-10-08T18:03:24.577 回答