-4

I have the folliwing code:

void main() 
{  
    int a=30,b=40,x;
    x=(a!=10) && (b=50);  
    printf("x=%d",x);
}

Here in the result I get x=1. In && operator the condition true only when both are true here the first is true i.e a not equal to 10 , but second is b=50 which is wrong then also the value of x is 1 in out put. Why is this happening ?

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
Gunjan Raval
  • 141
  • 8

4 Answers4

4

In your code, change

 ... && (b=50);

to

 ... && (b == 50);

Otherwise, the value of b, after the assignement, will be considered as the second expression of the && operator.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
4

The second comparison is actually an assignment. It should be:

x=(a!=10) && (b==50);
dbush
  • 205,898
  • 23
  • 218
  • 273
2

You are using the assignment operator = rather than the equivalence test == operator against b.

Fixed Code Listing


#include <stdio.h>

void main()
{
    int a=30, b=40, x;
    x = ((a!=10) && (b==50));
    printf("x=%d",x);
}

A good strategy to prevent this in the future is to swap your LVALUE and RVALUE, so your code looks like this:

    x = ((10 != a) && (50 == b));

If you adhere to the above style, if you make the same mistake in the future, you would end up with:

50 = b

Which would trigger a compilation error, since you can't assign a variable RVALUE to a constant/literal LVALUE.

Cloud
  • 18,753
  • 15
  • 79
  • 153
0

Expression (b=50) has logical value 1 (true), not 0 (false).

CiaPan
  • 9,381
  • 2
  • 21
  • 35