Are there any problems with this Boolean based C programming question?
In order to understand how the code executes and gives the final result, the key is to understand the operator precedence.
Among the three logic operators, namely logic not !
, logic and &&
,and logic or ||
, logic not !
has the highest precedence, then logic and &&
and then comes logic or ||
.
The logic not !
has a higher precedence than logic and &&
and logic or ||
, so the a&&b
and !c&&d
both evaluate to false
.
Because (a&&b)||(!c&&d)
evaluates to false, the outer if
body doesn't execute.
Now, it comes into the outer else section.
d&&c
evaluates to false because both d
and c
are false. As a result, !(d&&c)
evaluates to true. Of course not a !a
evaluates to true too.
In the end, !(d&&c)&&(!a)
is true. So printf("4");
executes and output a 4