6

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;
}
2
  • 2
    Because of operator precedence rules, x && y == 1 = x && (y == 1) Commented Feb 24, 2015 at 16:07
  • 1
    You probably meant something like (x && y) == 1.. but x && y is preferable. Commented Feb 24, 2015 at 16:07

4 Answers 4

6

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

Sign up to request clarification or add additional context in comments.

Comments

1
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.

2 Comments

It doesn't really help if you don't say anything about operator precedence.
Yeah . You're right. I mis-interpreted the question a bit and did not see "x && y gives 1. Still the output is false.". Now @Rizier123 has a correct answer to the question.
0

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!!!

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.