Lesson 5.4. Ternary Operator ?:

In C, there is a ternary operator ?:

The general syntax of this operator is:

(test) ? expressionTrue : expressionFalse ;

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);
Check Great! The test is false => the second expression that is evaluated. Try again...

What does the following code display?

int n=(2<3)?0:1;
putchar ('%d', n);
Check Great! The test is true => the first expression is evaluated. Try again...

Which instruction is equivalent to the code below?

if (x%2)
    c = 'p';
else
    c = 'i';
Check Great! The operator affects the expression that has been evaluated, you have to put the c= at the beginning. Try again...

See also


Last update : 11/22/2022