Lesson contents

C — Conditional operator (? :)

The conditional operator selects one of two expressions and evaluates only the selected operand. It can guard an operation that requires a nonzero divisor.

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.c
#include <stdio.h>

int main(void) {
    int n = 2;
    puts(n > 0 ? "positive" : "other");
}
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. Store the guarded integer result separately from its display label. When there are no samples, the placeholder zero is never presented as a measured average.

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 C17 compiler. Run these commands from the directory containing the example. Use a Unix-style shell.

cc -std=c17 -Wall -Wextra lesson.c -lm -o lesson
./lesson
lesson.c
#include <stdio.h>

int main(void) {
    int counts[] = {0, 3};
    for (int i = 0; i < 2; ++i) {
        int count = counts[i];
        int mean = count == 0 ? 0 : 18 / count;
        if (count == 0) puts("no samples");
        else printf("%d\n", mean);
    }
    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.

WG14 C language draft (PDF)

Related tags

  • C
  • conditional selection
  • expressions
  • zero division