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
- Start with n is 2
- Do this Choose by sign
- Result positive
#include <stdio.h>
int main(void) {
int n = 2;
puts(n > 0 ? "positive" : "other");
}
positive
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.
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
#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;
}
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.