Search code examples
cincrementpostfix-operatorprefix-operator

Why are expressions not processed after a postfix increment and a conjunction operator?


I bumped into a problem which prompted me to do some research. I have found that a piece of code like this:

#include <stdio.h>

int main(void)
{
    char i = 0;
    i++ && puts("Hi!");
    printf("%hhd\n", i);
}

only processes the increment, and outputs:

1

That is not the case if the postfix increment is replaced by a prefix one, it outputs:

Hi!
1

Why does it behave like that?

I apologise if the question is dumb.


Solution

  • In

    i++ &&  puts("Hi!");
    

    i is evaluated before the increment. Because it's 0 the second part of the expression no longer needs to be evaluated, 0 && 0 is 0, 0 && 1 is also 0.

    The same expression with a pre-increment means that i will be 1 when it's evaluated, in this case the second part of the expression is important, because 1 && 1 is possible, but 1 && 0 is also possible, and these will render different results.