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:
a
is initially 9.a--1
is evaluated and ignored. This changesa
to 8.a--2
is evaluated and tested. This changesa
to 7 and evaluates as 8. Since 8 is non-zero, thefor
execution continues.printf("%d\n",a);
is evaluated. This prints 7.a--3
is evaluated and ignored. This changesa
to 6.a--2
is evaluated and tested. This changesa
to 5 and evaluates as 6. Since 6 is non-zero, thefor
execution continues.printf("%d\n",a);
is evaluated. This prints 5.a--3
is evaluated and ignored. This changesa
to 4.a--2
is evaluated and tested. This changesa
to 3 and evaluates as 4. Since 4 is non-zero, thefor
execution continues.printf("%d\n",a);
is evaluated. This prints 3.a--3
is evaluated and ignored. This changesa
to 2.a--2
is evaluated and tested. This changesa
to 1 and evaluates as 2. Since 2 is non-zero, thefor
execution continues.printf("%d\n",a);
is evaluated. This prints 1.a--3
is evaluated and ignored. This changesa
to 0.a--2
is evaluated and tested. This changesa
to −1 and evaluates as 0. Since 0 is zero, thefor
execution ends.