Here is the program using a while loop,
#include <stdio.h>
int main()
{
int i;
i = 1;
while (i <= 32767)
{
printf("%d", i);
i = i + 1;
}
}
do you think the loop would execute indefinitely?
Here is the program using a while loop,
#include <stdio.h>
int main()
{
int i;
i = 1;
while (i <= 32767)
{
printf("%d", i);
i = i + 1;
}
}
do you think the loop would execute indefinitely?
Well it's signed integer. Considering that if int
is of 16 bits, it will overflow at one point precisely when the value is INT_MAX
or 32767
. At that point it is undefined behavior.
It is undefined behavior - when int
is of 16 bits. As the behavior is undefined we can't say it will always run infinitely etc in that case.
In your system if
int
is of32
bits or higher then the behavior of this program is not undefined.
From standard
.... Their implementation-defined values shall be equal or greater in magnitude (absolute value) to those shown, with the same sign.
In your case if sizeof(int) = 4
or higher, then the loop will stop. The only way to know whether the behavior is undefined or not is to know what the size of int
is.
int
is of 32 bits or higher then this will stop.int
is of 16 bits then this will be undefined behavior. It may loop indefinitely or it may not. It's not defined by the standard.If you disregard the specific numbers and instead write
while (i <= MAX_INT)
the compiler sees this as "loop while i
is less than or equal to the largest value it can ever have".
As i
- by definition - can never be larger than the largest value, this condition will always be true and the loop would be infinite.
However, as the code tries to compute i + 1
even when i
cannot possibly become any larger, there is an error in the program. The language standard explicltly states that if the program tries this - overflow on a signed variable - the result is undefined.
Undefined behavior can have any result according to the language standard. This includes getting some other value for i
(perhaps a negative one despite trying to add 1), having the OS trap and terminate the program, or possibly even terminate a loop that would otherwise be infinite. We just don't know.
I don't know your book. And in fact the book is correct if you assume that the type int
is a 16 bit signed integer. The range of a 16 bit integer goes from -32768 to +32767. So in this case the condition i<=32767
will always be true.
But in your programm I think the type of int
is a 32 bit integer which range goes from -2147483648 to +2147483647.
If you replace int i
with short i
the loop should be an infinity loop.