According to the short-circuit property in C:0&&(anything) gives 0 and 1||(anything) gives 1. so according to the property-0&&5||6&&7||4&&!6,this should give us 0.
But when I tried to run this in a C compiler this gave 1 as the answer.
[Update: removed image link, just typed in the program as text.]
#include <stdio.h>
int main()
{
int x;
x=0&&5||6&&7||4&&!6;
printf("%d",x);
return 0;
}
Can anybody tell me what am I missing or doing wrong?
Let me try explain what is happening, then you can follow along and find by yourself what you were missing.
Let's start with your original expression
This expression is written as a short form without any parentheses.
This is similar to standard mathematical expressions where
2*7+3*8is understood to mean that the*has precedence over+, so this is actually a short form for(2*7)+(3*8), and2*7+3*8+4*3is short form for((2*7)+(3*8))+(4*3).In the same way, the above C expression implicit operator precedence can be made explicit by rewriting with parentheses:
The above step appears to be what you are missing, and therefore you are misinterpreting the meaning of the written expression.
We can then consider the three small parentheses separately:
(0 && whatever)is0(short circuit applies)(6 && 7)is1(both 6 and 7 are non-zero i.e. true, so result is true)(4 && !6)isnonzero && zeroiszerois0(which, as it turns out later, we do not actually need to evaluate)So... the whole expression
turns out to be
or
which is
1.