# Lesson 5.4. Ternary Operator ?:

In C, there is a ternary operator `?:`

• this is a conditional operator : it check a condition (as an `if...else`).
• this is a ternary opérator because it takes 3 operands.

The general syntax of this operator is:

``(test) ? expressionTrue : expressionFalse ;``
• If the test is true, the first expression is evaluated (and assigned).
• If the test is false, the second expression is evaluated (and assigned).

This operator is mainly used when you want to assign different values depending on the test.

``````// If x not equal to 0, 10 is assigned to n. Otherwise, 20 is assigned to n
n = (x != 0) ? 10 : 20;``````

## Example

The example below assigns the variable `a` to `max` if `a` is greater than `b`, otherwise, the variable `b` is assigned to `max`. This instruction can be summarized in one sentence:

The variable `max` will contain the largest value between `a` and `b`. :

``max = (a > b) ? a : b;``

This instruction can also be written with an `if...else` :

``````if (a>b)
max = a;
else
max = b;``````

## Exercise

Write a program that asks the user to enter the number of kids. Then, the program displays : You have 7 kids. The word kid must be in the plural if the number entered is strictly greater than 1.

``````int nbKids;

// Get number of kids
printf ("How many kids? ");
scanf ("%d", &nbKids);

// Displays the number of kid(s)
printf ("You have %d kid%c.\n", nbKids, /* COMPLETE HERE */ );``````

Tip: ASCII code zero does not display anything.

Here is the expected output:

``````How many kids? 1
You have 1 kid.``````
``````How many kids? 7
You have 1 kids.``````

## Quiz

What does the following code display?

``````int n = (2>3) ? 0 : 1;
putchar ('%d', n);``````

What does the following code display?

``````int n=(2<3)?0:1;
putchar ('%d', n);``````

Which instruction is equivalent to the code below?

``````if (x%2)
c = 'p';
else
c = 'i';``````