Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fully understand prefix increment (++) operation

Tags:

c

I have the following code and I expect the output is:

foo(0) -- 2   /* 1*2 */
foo(2) -- 12  /* 3*4 */
foo(4) -- 30  /* 5*6 */

but I've got

foo(2) -- 4
foo(4) -- 16
foo(6) -- 36

instead. Can someone explain to me what happened?

include <stdio.h>

int main()
{
    int counter;    /* counter for loop */

    counter = 0;

    while (counter < 5)
        printf("foo(%d) -- %d\n", counter, ((++counter)*(++counter)));

    return (0);
}
like image 929
Dean Avatar asked Dec 04 '22 08:12

Dean


1 Answers

Once you've used ++ -- prefix or postfix -- on a variable, you can't use it again on the same variable until after the next sequence point. If you do, the behavior of the code is undefined -- the compiler is allowed to do anything it wants.

There are no sequence points between the two (++counter) expressions in your code, so you've run afoul of this rule. You have to write something like this, instead:

while (counter < 5) {
    printf("foo(%d) -- %d\n", counter, (counter+1) * (counter+2));
    counter += 2;
}
like image 191
zwol Avatar answered Dec 23 '22 18:12

zwol