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!"
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!"
It is called short circuit evaluation of a logical expression. Logical expressions are evaluated until the result is undetermined.
In this case:
x==0
logical AND will be false
despite the other side of the
expression. printf
will not be called.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.
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.