4
Contributors
3
Replies
5
Views
5 Years
Discussion Span
Last Post by Banfa
0

?: is an operator that works similar to an if construct except it can return a value when used on an expression. The syntax is [condition] ? [statement1] : [statement2]; where statement1 is executed if condition evaluates to true, statement2 otherwise.

Literally, that should evaluate to returning 'O' like char var = 'X' ? 'O' : 'X';

0

int var = (x) ? y : z;
is equavalent to this:
int var; if (x) var = y; else var = z;

Do note that inline conditional statements like this can only reliably return an integer or compatible type, though you can return pointers with the appropriate casts. Caveat programmer! :-)

Edited by rubberman

0

[condition] ? [statement1] : [statement2];

Strictly it is

[expression1] ? [expression2] : [expression3];

There are no such things as conditions in C only expressions and statements. Statements are not required to return a value but expressions are.

expression2 is evaluated if expression1 evaulates to true (any non-zero number) otherwise expression3 is evaluated. The value of the evaluated expressions (either 2 or 3) is returned.

Generally expression2 and expression3 must evaluate to the same type or you are likely to get warnings or errors from your compiler.

Edited by Banfa

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.