Sara
Sara

Reputation: 13

return statement with conditions ? and :

I am very beginner in c and I am reading now the classic example of the TicTacToe game. I am not sure about what this return statement does:

  {.....
     return (ch == X) ?O :X;

This must be some conditional statement on the variable ch (that in my case stands for the player (X or O) but I am not sure about its meaning. Can anyone please tell me what does it do?

Upvotes: 1

Views: 7007

Answers (4)

thefourtheye
thefourtheye

Reputation: 239483

The ... ? ... : ... operator is called ternary operator. Its a shorthand for simple if statement. Lets see few examples,

Odd/Even

n % 2 ? printf ("Odd") : printf ("Even");

OR

printf ("%s\n", n % 2 ? "Odd" : "Even");

Factorial

int factorial(int n)
{
    return (n == 0 ? 1 : n * factorial (n - 1));
}

Upvotes: 0

SBI
SBI

Reputation: 2322

This is called a ternary operator, because unlike many other operators, it doesn't take one or two operands, but three. A boolean condition and two values. In your example, if the boolean condition (ch == X) validates to true, O is the result of the operator. Otherwise, X is the result.

This can be rewritten as:

if (ch == X)
    return O;
else
    return X;

Upvotes: 6

zaerymoghaddam
zaerymoghaddam

Reputation: 3127

It means

if (ch == X) 
    return O;
else
    return X;

Upvotes: 6

alk
alk

Reputation: 70941

If ch equals X return O else return X.

Upvotes: 1

Related Questions