Lesson contents

C++ — Conditional expressions with ?:

The C++ conditional operator evaluates its condition and exactly one result expression. Giving the branches compatible types makes the selected value easy to store.

A simple example

Choose one value

  1. Start with n is 2
  2. Do this Choose by sign
  3. Result positive
The condition selects which word becomes the result.
lesson.cpp
#include <iostream>

int main() {
    int n = 2;
    std::cout << (n > 0 ? "positive" : "other") << '\n';
}
Output
positive
Advertisements

Choose a report value when a sample is missing

Report a whole-number average for a nonempty group and a text label for an empty group. Guard the division where the result is selected. std::to_string runs only when count is nonzero. Both choices can produce the std::string used for the report.

Empty group: No samples. Measured group: 18 ÷ 3. Display: 6.
Handle an empty reading

A monitor displays the average of a sensor’s samples. If no sample arrived, show a message before attempting division. Three samples with a total of 18 give an average of 6.

Run the example

Use a C++17 compiler. Run these commands from the directory containing the example. Use a Unix-style shell.

c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lesson
lesson.cpp
#include <iostream>
#include <string>

int main() {
    for (int count : {0, 3}) {
        std::string text = count == 0 ? "no samples" : std::to_string(18 / count);
        std::cout << text << '\n';
    }
    return 0;
}
Output
no samples
6

The first group has zero samples and displays no samples. In the second group, 18 divided by 3 gives 6.

Try it yourself

What does an observed total of zero with three samples display?

Check your answer

It displays 0. This is a measured zero, whereas the empty group has no average.

C++17 working draft

Related tags

  • C++
  • conditional selection
  • expressions
  • zero division