Search code examples
cpre-increment

Why the first two variables (a, b) are pre-incremented but the third one is not(c)?


I am having an issue I cannot understand. The output for a is 6, b is -6 but the c remains the same no matter what variable I initialize it with.

#include <stdio.h>
void main()
{
int a = 5, b = -7, c = 0, d;
d = ++a && ++b || ++c;
printf("\n%d%d%d%d", a, b, c, d);
}

Thank you.


Solution

  • This is short-circuiting behavior, and a deliberate part of the C language.

    When C finds an expression of the form:

    (expression A) || (expression B)
    

    And expression A is evaluated to be TRUE, it does not matter what expression B is!
    It could be TRUE, or FALSE, but the overall expression will still be TRUE, because of the ||.

    As a result, the C language will not even bother to evaluate the second-half: expression B. That part just gets skipped, and so the ++c is skipped and never evaluated.


    Just for kicks, if you wanted to change this program so that ++c does happen, set b equal to -1, so that when you have ++b, it becomes 0 (false).

    int a = 5, b = -1, c = 0, d;
    

    Now, the expression will evaluate this way:

    d = (6 && 0) || [ lazy, short-circuit evaluation ];
    d =    0     || [ second expression is now required! ];
    d =    0     ||  1;
    d = 1;
    

    Output:

    6011