1

How does this work?

int x = 0;
x && printf("Hello World!");

This will output nothing on terminal, but

int x = 1;
x && printf("Hello World!");

will output "Hello Wolrd!"

bralebr
  • 19
  • 2
  • 4
    Welcome to Stack Overflow. How well do you understand `&&`? – Beta Jan 29 '22 at 18:21
  • 1
    bralebr, Tip: Best to cut and paste true output text than re-type with a transcription error. – chux - Reinstate Monica Jan 29 '22 at 18:30
  • 2
    Oh! I get it now. So first the left side of the expression is going to be evaluated, if its false then there's no need to evaluate the second expression. Therefore, the printf() isn't executed, rigth? @Beta – bralebr Jan 29 '22 at 18:33
  • That's the [short-circuit rule](https://en.wikipedia.org/wiki/Short-circuit_evaluation). When `x == 0` the whole expression must be false without needing to evaluate `printf()`. – Weather Vane Jan 29 '22 at 18:34
  • Exactly right. (And you got it before anyone answered!) – Beta Jan 29 '22 at 18:57

2 Answers2

2

It is called short circuit evaluation of a logical expression. Logical expressions are evaluated until the result is undetermined.

In this case:

  • if x==0 logical AND will be false despite the other side of the expression. printf will not be called.
  • if x==1 the result of AND is still undetermined. printf will be called.

The result of this AND operation is not used and compiler will warn you.

0___________
  • 60,014
  • 4
  • 34
  • 74
  • It's called short circuit, not short hand. And I think you meant to say "determined" instead of "undetermined" in the first paragraph. – interjay Jan 29 '22 at 18:39
1

The C standard specifies the behavior of && in clause 6.5.13. Paragraph 4 says:

Unlike the bitwise binary & operator, the && operator guarantees left-to-right evaluation; if the second operand is evaluated, there is a sequence point between the evaluations of the first and second operands. If the first operand compares equal to 0, the second operand is not evaluated.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312