I am trying to figure out the following code:
#include <stdio.h>
#define TEN 10
int main(void)
{
int n = 0;
while (n < TEN)
printf("]", n);
return 0;
}
This prints 1 through 10. Isn't it supposed to print 1 to 9 only, since n
will make it 10, and the condition while (10 < TEN) would fail hence should exit before printing?
When I change it to while ( n < TEN)
I get 1 to 9, which makes sense because the addition is made before the check.
My so far understanding is that the n
will add after the condition has been checked, hence it will print 10 (since n
checks before, and n
check after). Is that correct?
Thanks!
CodePudding user response:
With n
(postfix increment operator), the value of n
gets incremented after the while
statement, therefore the while condition n < TEN
is first verified, and only after the value of n
is updated.
When the last iteration of your while instruction while (n < TEN)
is executed, n
is still 9 (and gets incremented by 1 right after) that's why it prints 10 as the last value:
1 2 3 4 5 6 7 8 9 10