Today I had a test on C at my university and one of the questions asked to give the output for this block of code:
int a=9;
for(a--;a--;a--)
printf("%d\n",a);
I thought this would create an infinite loop but on checking it gave
7
5
3
1
as output. Why did it not create an infinite loop? What's going on in this program?
CodePudding user response:
If you separate the post-decrement into separate statements this is the equivalent code:
#include <stdio.h>
int main(void) {
int a = 9;
a--;
while(a) {
a--;
printf("%d\n", a);
a--;
}
return;
}
Program output:
7
5
3
1
This won't stop when a is even, unless the condition is changed to
while(a > 0)
CodePudding user response:
Labeling the parts of the for statement:
for(a--1; a--2; a--3)
printf("%d\n",a);
it is executed:
ais initially 9.a--1is evaluated and ignored. This changesato 8.a--2is evaluated and tested. This changesato 7 and evaluates as 8. Since 8 is non-zero, theforexecution continues.printf("%d\n",a);is evaluated. This prints 7.a--3is evaluated and ignored. This changesato 6.a--2is evaluated and tested. This changesato 5 and evaluates as 6. Since 6 is non-zero, theforexecution continues.printf("%d\n",a);is evaluated. This prints 5.a--3is evaluated and ignored. This changesato 4.a--2is evaluated and tested. This changesato 3 and evaluates as 4. Since 4 is non-zero, theforexecution continues.printf("%d\n",a);is evaluated. This prints 3.a--3is evaluated and ignored. This changesato 2.a--2is evaluated and tested. This changesato 1 and evaluates as 2. Since 2 is non-zero, theforexecution continues.printf("%d\n",a);is evaluated. This prints 1.a--3is evaluated and ignored. This changesato 0.a--2is evaluated and tested. This changesato −1 and evaluates as 0. Since 0 is zero, theforexecution ends.
