C Relational Operator Output
Solution 1
This is due to the Short Circuit mechanism.
What this means is that when the result of a logical operator is already determined, the rest of the expression isn't evaluated at all, including potential side effects.
The first code fragment behaves like:
int a = (1 && 0) /* result pending... */ || z++;
And the second:
int a = (1 && 0) /* result determined */;
This happens because the value of a logical AND is known to be false if the left side expression is false.
Solution 2
As you can probably tell, the difference between two fragments of code is that the first one evaluates z++
, while the other one doesn't.
The reason the second code does not evaluate z++
is that the expression ahead of it evaluates to false
, so &&
chain "short-circuits" the evaluation of the last term.
Operator ||
, on the other hand, would short-circuit only when the left side is true
.
Solution 3
For starters function main without parameters shall be declared like
int main( void )
In the first program the initialization expression can be represented like
int a = ( x && y ) || ( z++ );
According to the C Standard (6.5.14 Logical OR operator)
- ...If the first operand compares unequal to 0, the second operand is not evaluated.
The first oerand ( x && y )
of the expression is equal to 0 because y is initialized by 0
int x = 1, y = 0, z = 5;
So the second operand ( z++ )
is evaluated.
As result z will be equal to 6.
In the second program the initialization expression can be represented the same way as in the first program
int a = ( x && y ) && ( z++ );
According to the C Standard (6.5.13 Logical AND operator)
- ...If the first operand compares equal to 0, the second operand is not evaluated.
As before the first operand ( x && y )
of the expression is equal tp 0 and according to the quote the second operand ( z++ )
is not evaluated.
As result z will be equal to 5 as before.
Admin
Updated on June 04, 2022Comments
-
Admin almost 2 years
#include <stdio.h> void main() { int x = 1, y = 0, z = 5; int a = x && y || z++; printf("%d", z); }
This yields output as 6 whereas
#include <stdio.h> void main() { int x = 1, y = 0, z = 5; int a = x && y && z++; printf("%d", z); }
this would yield answer as 5. WHY ?? Someone please explain.