C Integer division guard
Check the number of students before dividing an integer fee.
A simple example
Integer division guard
- Start with 4 divided into zero groups
- Do this Attempt integer division or check the divisor
- Result Division cannot proceed
Syntax
students == 0
Run these examples in C
Save one example at a time as lesson.c. Use C17 and a Unix-style shell.
cc -std=c17 -Wall -Wextra lesson.c -lm -o lesson
./lessonSplit an equipment fee across a class
A training center shares a fixed equipment fee among the students registered for a workshop. When the last student cancels, the fee calculator should show a message before it divides by the headcount.
#include <stdio.h>
int main(void) {
int students = 0;
int fee = 120;
if (students == 0) {
puts("No students registered");
} else {
printf("%d\n", fee / students);
}
return 0;
}
No students registered
The workshop has zero students, so the calculator cannot assign anyone a share of the fee.
Split a studio hire fee
Two groups register for a 24-credit rehearsal. Divide the total among the registered groups using whole-number division. The desk puts the batch on hold if the divisor is zero.
Hold an empty field-trip batch
A trip has a 30-credit fixed fee and no groups registered yet. Divide the total among the registered groups using whole-number division. The desk puts the batch on hold if the divisor is zero.
What to watch for
Integer division by zero has undefined behavior in C. A post-division error check cannot make it safe.