The Ternary Operator

C has an alternative syntax for the if-else conditional, referred to as the ternary (or trinary) operator. The name stems from the fact that there are three parts to using the operator. The basic syntax of it is

(condition) ? true_result :

					false_result;

What is notable about this operator is that it returns one of two values based on a condition. This returned value is normally assigned to a variable or printed. For example, the following will return a value indicating whether a number is even or odd (it uses the modulus operator to see if there's a remainder when the number is divided by 2):

char even_odd;
even_odd = ( (number % 2) == 0) ? 'e' :
'o';

Rewritten as a conditional, it would be

char even_odd;
if ( (number % 2) == 0) {
   even_odd = 'e';
} else {
   even_odd = 'o';
}

In this next example, the ternary operator will be used to print an appropriate message depending on the temperature.

To use the ternary operator

1.
Create a new, blank C project in your text editor or IDE.

2.
Add the initial comments and code (Script 4.4):

/* weather.c - Script 4.4 */
#include <stdio.h>
int main (void) {

Script 4.4. The ternary operator can often be used as shorthand for if-else conditionals, returning one of two values depending on the truth of its condition.


3.
Declare and initialize an integer variable:

int temperature = 102;

This variable will store the current temperature as degrees Fahrenheit in an integer value.

4.
Begin the main if conditional:

if (temperature > 90) {
     printf ("At %d degrees, it's
 hot, hot, hot outside!
",
 temperature);

The first clause of the conditional checks to see if it's over 90 degrees. If so, the printf() statement prints the temperature and states that it's hot outside (for those who like applications that point out the obvious).

5.
Add an else if clause with a ternary operator as part of its print statement:

} else if (temperature < 40) {
 printf ("At %d degrees, it's %s
 outside!
", temperature,
 (temperature < 20) ? "freezing" :
 "cold" );

If the temperature is below 40 degrees, the application will print that it's either freezing or cold outside. Rather than having another else if clause, this is accomplished using the ternary operator within the printf() statement.

The %s marker in the printf() statement is the placeholder for a string to be determined by the ternary operator, which is the third argument (after temperature, which corresponds to %d in the quote). The condition of the ternary operator checks if the temperature is below 20 degrees. If it is, the word freezing is returned. If that conditional is false, the word cold is returned. Note that both returned words are in double quotes, as they are strings.

6.
Complete the conditional:

} else {
    printf ("At %d degrees, it's a
 relatively temperate day.
",
 temperature);
}

Finally, if it's not over 90 degrees (the first condition) or under 40 (the second), it's assumed to be a temperate day.

7.
Complete the main() function:

   getchar();
   return 0;
}

8.
Save the project as weather.c.

9.
Compile and debug, as necessary.

10.
Run the executable application (Figure 4.9).

Figure 4.9. If the temperature is above 90 degrees, the first printf() statement is executed (see Script 4.4).


11.
For comparison, change the value of temperature, recompile, and rerun the application (Figure 4.10).

Figure 4.10. If the temperature is below 40 degrees, it will be described as either freezing or cold, thanks to the ternary operator.


✓ Tips

  • As a variation on the weather application, you could change the first conditional to check if it's over 70 degrees, then add a printf() with a ternary operator as its statement, reporting on weather it's warm or hot.

  • The main benefit of using the ternary operator instead of an if-else conditional is that it makes for shorter code. This is at the expense of some legibility. If you find the format to be too confusing, stick with the if structure.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset