0

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.

anastaciu
  • 23,467
  • 7
  • 28
  • 53
Kaiyaha
  • 448
  • 3
  • 9
  • 2
    Read about *short-circuit evaluation* of logical operators. – Eugene Sh. Sep 23 '20 at 21:32
  • 2
    `&&` and `||` do short circuit evaluation. If you say `x && y` then if x is false (0) then the whole expression is false and so the `y` part doesn't need to be evaluated. And, in your program i *is* false (0) because it is incremented AFTERWARDS (it is a post increment) – Jerry Jeremiah Sep 23 '20 at 21:33
  • Possible duplicate: https://stackoverflow.com/questions/5211961/how-does-c-handle-short-circuit-evaluation https://stackoverflow.com/questions/628526/is-short-circuiting-logical-operators-mandated-and-evaluation-order – Jerry Jeremiah Sep 23 '20 at 21:35
  • It does not look like `i++` supposed to be evaluated as `true` of `false` – Kaiyaha Sep 23 '20 at 21:36
  • `i++` evaluates to 0, and `i` gets incremented. So the left side of the logical AND is false, and the right side doesn't need to be evaluated. – user3386109 Sep 23 '20 at 21:36
  • Anything in C can be evaluated as `true` and `false`. – Eugene Sh. Sep 23 '20 at 21:37
  • 1
    Everything is treated as true or false if it is part of a logical expression (like one containing `&&` or `||`) - a value of 0 is false and anything else is true. – Jerry Jeremiah Sep 23 '20 at 21:37

1 Answers1

2

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.

anastaciu
  • 23,467
  • 7
  • 28
  • 53