#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.
The output of the relational operator is (true/false) boolean value, and in Java, true or false is a non-numeric value that is not related to zero or one.
C Relational Operators A relational operator checks the relationship between two operands. If the relation is true, it returns 1; if the relation is false, it returns value 0. Relational operators are used in decision making and loops.
-= Subtract AND assignment operator. It subtracts the right operand from the left operand and assigns the result to the left operand. C -= A is equivalent to C = C - A.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With