0

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("%5d", 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!

F.A
  • 297
  • 1
  • 3
  • 13
  • Read up on pre-increment and post-increment operators. – Dúthomhas Oct 04 '22 at 20:49
  • The value evaluated in the `if` statement for `++n` is `n + 1`, for `n++` it is `n`. – Retired Ninja Oct 04 '22 at 20:50
  • It prints 1 greater than the value that was tested (because it was incremented after testing). – Weather Vane Oct 04 '22 at 20:50
  • Take a look here: https://en.cppreference.com/w/c/language/operator_incdec – nielsen Oct 04 '22 at 20:50
  • 1
    [Difference between pre-increment and post-increment in a loop?](https://stackoverflow.com/questions/484462/difference-between-pre-increment-and-post-increment-in-a-loop) may be helpful. It asks about a `for` loop which is a little different but there is discussion about the difference between pre and post. – Retired Ninja Oct 04 '22 at 20:56

1 Answers1

1

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
mikyll98
  • 1,195
  • 3
  • 8
  • 29