2

I have a problem in C.

#include<stdio.h>
int main()
{
    int a = 10, b = 0, c = 7;
    if (a ? b : c == 0)
        printf("1");
    else if (c = c || a && b)
        printf("2");
    return 0;
}

This code prints 2 but I think a?b:c returns b=0 and 0==0 returns 1. Can you explain the code?

another.anon.coward
  • 11,087
  • 1
  • 32
  • 38
user1094138
  • 59
  • 2
  • 6
  • 3
    Why don't you just look up the operator precedence table? Such kinds of questions are useless otherwise. – Blagovest Buyukliev Apr 04 '12 at 08:06
  • If you know this is about precedence, why don't use the [precedence order](http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Operator_precedence) to figure out where to put parentheses? – Oliver Charlesworth Apr 04 '12 at 08:06

2 Answers2

8

The conditional operator (?:) has one of the lowest precedences. In particular it is lower than ==. Your statement means this:

if(a ? b : (c == 0)) { ... }

Not this:

if((a ? b : c) == 0) { ... }
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
4

Your conditions are not properly written.

In the first if-statement:

  if (a ? b : c == 0)

if you put the values, then it becomes

if(10 ? 0 : 7 == 0)

means, it will always return 0.

That's why control goes to the else part and there, it becomes

else if (7 = 7 || 10 && 0)

since you used the "=" operator here (c = c), it will be always true, therefore it prints "2".

Now you want that code should return "1", then change your if statement in this way.

 if( (a ? b:c) == 0){...}

because "==" operator has higher precedence than ternary operator.

Alexis Wilke
  • 19,179
  • 10
  • 84
  • 156
Nishu Tayal
  • 20,106
  • 8
  • 49
  • 101