Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Program output confusion

Tags:

c

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;
}
like image 921
Apoorva Somani Avatar asked Feb 24 '15 16:02

Apoorva Somani


2 Answers

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

like image 91
Rizier123 Avatar answered Oct 12 '22 06:10

Rizier123


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.

like image 25
Spikatrix Avatar answered Oct 12 '22 07:10

Spikatrix