Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Value after the while loop with post-increment

Please explain me why the last printf gives value 11? I really don't understand why it happened. When a = 10 the condition is not fulfilled so why this value has changed to 11? Incrementation goes as soon as the condition is checked?

Code:

int main(void) {
    int a = 0;
    while(a++ < 10){
        printf("%d ", a);
    }
    printf("\n%d ", a);
    return 0;
}

Output:

1 2 3 4 5 6 7 8 9 10 
11 
like image 460
pb. Avatar asked Jun 02 '26 18:06

pb.


2 Answers

Let's look at a++ < 10 when a is equal to 10.

The first thing that will happen is 10 < 10 will be evaluated (to false), and then a will be incremented to 11. Then your printf statement outside the while loop executes.

When the ++ comes on the right hand side of the variable, it's the last thing evaluated on the line.

Try changing a++ < 10 to ++a < 10, rerunning your code, and comparing the results.

like image 168
nhgrif Avatar answered Jun 05 '26 12:06

nhgrif


The post increment operator increments the value of the variable before it after the execution of the statement.

Let's take an example,

int k = 5 ;
printf("%d\n", k++ );
printf("%d", k );

will output

5
6

because in the first printf(), the output is shown and only after that, the value is incremented.

So, lets look at your code

while(a++ < 10)

it checks a < 10 and then after that, it increments a.

Lets move to a few iterations in your loop.

When a is 9, the while loop checks 9 < 10 and then increments a to 10, so you will get output for that iteration as 10, and similarly, for the next iteration, it will check 10 < 10 but the while loop does not execute, but the value of a is incremented to 11 and thus, in your next printf() , you get output as 11.

like image 40
Arun A S Avatar answered Jun 05 '26 14:06

Arun A S



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!