Library contents

C++ Checked integer division

Compare the count to zero before evaluating the integer division.

A simple example

Checked integer division

  1. Start with 4 divided into zero groups
  2. Do this Attempt integer division or check the divisor
  3. Result Division cannot proceed
A divisor of zero has no valid integer quotient. A guard or handler can select a fallback.

Syntax

C++ syntax
students == 0
Run these examples in C++

Save one example at a time as lesson.cpp. Use C++17 and a Unix-style shell.

c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lesson

Split 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.

From the programint students = 0
ResultNo students registered
lesson.cpp
#include <iostream>

int main() {
    int students = 0;
    if (students == 0) {
        std::cout << "No students registered\n";
    } else {
        std::cout << 120 / students << '\n';
    }
    return 0;
}
Output
No students registered

The workshop has zero students, so the calculator cannot assign anyone a share of the fee.

Advertisements

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.

Given24 credits / 2 groups
Worked resultShare calculated

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.

Given30 credits / 0 groups
Worked resultHold batch

What to watch for

Integer division by zero has undefined behavior. A try/catch around it cannot provide a portable recovery.

Documentation for Checked integer division