Statement with ? in C [duplicate]
-
28-09-2019 - |
Question
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.
Solution
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
.
OTHER TIPS
It assigns to A
the value of B
if A
is true, otherwise C[0]
.
result = a > b ? x : y;
is identical to this block:
if (a > b) {
result = x;
}
else
{
result = y;
}
It's the same as an if else
statement.
It could be rewritten as:
if ( A != 0 )
{
A = B;
}
else
{
A = C[ 0 ];
}
A gets assigned to B if A exists (not NULL), otherwise C[0].
if A equal 0 then A = C[0] else A = B