-4

I have the following C block of code with two while loops.

#include <stdio.h>

int main()
{
    int a = 0, b = 0;

    while (a++ <= 3)
    {
        printf("cycle a = %d\n", a);
    }

    while (++b <= 3)
    {
        printf("cyclo b = %d\n", b);
    }

    return 0;
}

The output for the first while is:

ciclo a = 1
ciclo a = 2
ciclo a = 3
ciclo a = 4 

The output for the second while is:

ciclo b = 1
ciclo b = 2
ciclo b = 3

What`s the reason for the different results in the while loops?

Jay Craig
  • 133
  • 6
  • [Pre vs. Post increment](https://en.cppreference.com/w/c/language/operator_incdec). – WhozCraig Feb 01 '22 at 11:48
  • This seems like some kind of homework. Just copying the homework question here is unlikely to get good reception. Instead, you should ask about something _you_ don't understand, explain how _you_ are stumped with this question, and what you have thought. – hyde Feb 01 '22 at 11:52
  • Do these answer your question?: [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); [Is there any difference in using pre increment and post increment in repetition control statements?](https://stackoverflow.com/questions/53877953/is-there-any-difference-in-using-pre-increment-and-post-increment-in-repetition); [What is the difference between ++i and i++?](https://stackoverflow.com/questions/24853/what-is-the-difference-between-i-and-i) – user17732522 Feb 01 '22 at 11:57
  • @hyde This is not a homework. I am reproducing a problem that I faced, and would like to know the reason, simple as that. – Jay Craig Feb 01 '22 at 12:00
  • Sadly, rarely is an accurate description (caveats, nuance, et'al) of postfix operators in an expression context portrayed, and unfortunately the answers below are no exception to that snake pit. – WhozCraig Feb 01 '22 at 12:17

2 Answers2

2

For this you need to understand how post-increment and pre-increment operator ++ works.

while (a++ <= 3)

Here post increment is used, meaning condition is checked first and the a is incremented.

while (++b <= 3)

Pre-increment: b is incremented and condition is checked later.

You can see now that, why first loop output is different than the second.

Vikram Dattu
  • 801
  • 3
  • 8
  • 24
2

First one is postfix increment, second one is prefix increment. You can check the while condition like this;

a++ <= 3(Firstly check a and increment a value)
Check   Output

0<=3     1
1<=3     2
2<=3     3
3<=3     4

++b <= 3(Firstly increment value and check b)

Check   Output

1<=3     1
2<=3     2
3<=3     3
Ogün Birinci
  • 598
  • 3
  • 11