What does 'X' ? 'O' : 'X' mean?

Thanks. :)

Recommended Answers

All 3 Replies

?: 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';

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! :-)

[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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.