6

Possible Duplicate:
How do I use the conditional operator?

I’m new to C language, and in one of the sample codes I was reviewing I faced the statement:

A = A ? B: C[0]

I was just wondering what the task of the previous statement is and what will be the result after execution of the mentioned statement.

Community
  • 1
  • 1
user435245
  • 859
  • 4
  • 16
  • 28

6 Answers6

14

It's called a ternary operator. expr ? a : b returns a if expr is true, b if false. expr can be a boolean expression (e.g. x > 3), a boolean literal/variable or anything castable to a boolean (e.g. an int).

int ret = expr ? a : b is equivalent to the following:

int ret;
if (expr) ret = a;
else ret = b;

The nice thing about the ternary operator is that it's an expression, whereas the above are statements, and you can nest expressions but not statements. So you can do things like ret = (expr ? a : b) > 0;

As an extra tidbit, Python >=2.6 has a slightly different syntax for an equivalent operation: a if expr else b.

moinudin
  • 134,091
  • 45
  • 190
  • 216
4

It assigns to A the value of B if A is true, otherwise C[0].

?:

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
3

result = a > b ? x : y; is identical to this block:

if (a > b) {
  result = x;
}
else
{
  result = y;
}
robert
  • 33,242
  • 8
  • 53
  • 74
3

It's the same as an if else statement.

It could be rewritten as:

if ( A != 0 )
{
    A = B;
}
else
{
    A = C[ 0 ];
}
Nick
  • 25,026
  • 7
  • 51
  • 83
1

A gets assigned to B if A exists (not NULL), otherwise C[0].

Neil
  • 5,762
  • 24
  • 36
  • -1 the inexistence of A makes the code not even compile. A can be `NULL`, `0` (int), `0.0` (double), etc ... – pmg Nov 25 '10 at 11:21
  • And it's B gets assigned to A. – Matthew Flaschen Nov 25 '10 at 11:26
  • Thought it was implied that if I said not NULL that I was refering to a pointer, not a double, int, etc. And A gets assigned to B, not vice versa. – Neil Nov 25 '10 at 11:32
  • @Neil: B does not change value with the expression in this question. Neither does C ... A (possibly) changes value. – pmg Nov 25 '10 at 11:35
  • A gets assigned to B. At what point did I say that B changes (or even C for that matter)? A takes on the value of B is what I meant by that. – Neil Nov 25 '10 at 11:48
  • @Neil: you're using the English language in an unusual way: in "A gets assigned to B" it is B that changes value. Compare with "The prize was assigned to Mark" ... :-) – pmg Nov 25 '10 at 11:55
  • I know. :( I only understood that second interpretation now. – Neil Nov 25 '10 at 12:33
1

if A equal 0 then A = C[0] else A = B

Sergey K
  • 4,071
  • 2
  • 23
  • 34