1

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?

4

4 Answers 4

6

It means

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

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;
1

If ch equals X return O else return X.

0

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));
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.