Is it possible for an integer variable to achieve the value -1 using the following C code -
main()
{
int n=0;
while(n++ != -1){
printf("\n%d",n);
}
}
Is it possible for an integer variable to achieve the value -1 using the following C code -
main()
{
int n=0;
while(n++ != -1){
printf("\n%d",n);
}
}
Yes, it is. At a certain point, the variable will overflow and may become negative. But note that signed overflow is undefined behavior, so there is no way to know what will happen, and this is the reason why such code should be avoided.
There is a theoretical and a practical part to this:
Theoretically, adding one to the max value of an integer will result in undefined behaviour. That may be anything. Pink elephants could be raining from the sky.
In practice, pink elephants were too difficult to implement even for compiler vendors and most of them will simply produce the minimum of the value range if you add one to the maximum of the value range. That means max+1 will result in min.
That way, once you counted from 0 to max, add one to reach min and count up to -1 again, yes, after some time in practice your integer will become -1.
By default, int
variables are signed
in C. So, in this case the signed
integer overflow invoke undefined behavior. n
may or may not become -1
.
But if you want to achieve this then declare n
as unsigned int
. Due to integer overflow you will get -1
.