I just came across this C question with the following code:
int fun();
int main()
{
for (fun(); fun(); fun())
printf("%d\n", fun());
return 0;
}
int fun()
{
int static n = 10;
return n--;
}
I expected the for loop to evaluate to for(10;9;8) and the printf to print 7 (since we would be calling fun() with n = 7?) but it prints 8. Why does this happen?
The answer is correct. In initialization
n becomes 10.condition1- n = 9Then
print1-8printedupdate-7condition2-6print2 - 5 printedand so on
The first answer was edited since on checking it was wrong.
Note:-the answer was to convert postfix to prefix which broke the code on testing
Update:- The reason
prefix incrementdid not work was because condition was not checked with 0 but with-1and2. There was no checking with0. Hence an infinite loop