Ad

While2.c In C Primer Plus

- 1 answer

The original code is as follows:

#include <stdio.h>
int main(void)
{
    int n = 0;

    while (n++ < 3);
        printf("n is %d\n", n);

    return 0;
}

I wonder why the result is "n is 4" not "n is 3"?

Ad

Answer

what happens here is that you compare to a good value, lets say 2 < 3, then the postincrement happens and you end up with 3 inside the loop

An example:

// you probably want to remove the ; at the end of the while like this:
while (n++ < 3) { // the posticrement will update the value n
    printf("n is %d\n", n); // here n will have an updated value
}

It is also a good practive to use {} instead of indentation.

Ad
source: stackoverflow.com
Ad