Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Statement with ? in C [duplicate]

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.

like image 354
user435245 Avatar asked Nov 25 '10 11:11

user435245


4 Answers

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.

like image 190
moinudin Avatar answered Nov 14 '22 23:11

moinudin


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

?:

like image 39
Ignacio Vazquez-Abrams Avatar answered Nov 15 '22 00:11

Ignacio Vazquez-Abrams


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

if (a > b) {
  result = x;
}
else
{
  result = y;
}
like image 3
robert Avatar answered Nov 14 '22 23:11

robert


It's the same as an if else statement.

It could be rewritten as:

if ( A != 0 )
{
    A = B;
}
else
{
    A = C[ 0 ];
}
like image 3
Nick Avatar answered Nov 14 '22 23:11

Nick