Reputation: 515
Can someone explain why the output of this program is false??
x && y gives 1. Still the output is false.
#include <stdio.h>
int main()
{
int x = 1, y = 2;
if(x && y == 1)
{
printf("true.");
}
else
{
printf("false.");
}
return 0;
}
Upvotes: 6
Views: 222
Reputation: 1092
It's okay to false, then 2 and 2 and it is different from one. What you're asking is whether both x and y both are worth 1. If this happens say true but false
Upvotes: 0
Reputation: 11
It clearly stated X = 1 & Y = 2; Now with your expression
X && Y == 1
The expression is evaluated as Y == 1 (Precedence Rule, Also output is False)
X != 0 (Its True)
Now && is Logical And Operator, so it evaluates to True only if both the parts in expression evaluates to True!!!
Upvotes: 0
Reputation: 20244
if(x && y == 1)
Is the same as
if( ( x != 0 ) && ( y == 1 ) )
Here,x != 0
is true, but y == 1
is false. And since at least one of the operands of &&
is false, the condition evaluates to false and the else
part executes.
Upvotes: 1
Reputation: 59701
Because ==
has a higher precedence than &&
So first this get's evaluated:
x && (y == 1)
y == 1 // 2 == 1
//Result: false
Which is false and then second:
x && false //1 && false
//Result: false
So the if statement will be false
For more information about operator precedence see here: http://en.cppreference.com/w/cpp/language/operator_precedence
Upvotes: 6