I was trying an experiment and I expected this code to throw an exception or print ambiguous value for n and exit but its end up running infinitely. Why it runs infinitely?
#include <stdio.h>
int main() {
int y=5;
int n=4;
while(y || n) {
printf("n = %d y = %d\n",n,y);
y--;
n--;
}
return 0;
}
CodePudding user response:
The loop runs as along a y
OR n
are non-zero.
For the loop to terminate, y
and n
would both have to be zero at the top of the loop, but that never happens because y
and n
start off not being equal to each other and each of them goes down by one each iteration.
Also note that signed integer overflow/underflow is undefined behavior, so if you run the loop long enough for that to happen, there are no guarantees about what will happen.