Skip to main content
The / operator is a binary arithmetic operator that computes the quotient of its first operand (the dividend) divided by its second operand (the divisor). It has left-to-right associativity, requires operands of arithmetic or unscoped enumeration types, and is subject to standard C++ usual arithmetic conversions. While the operator associates left-to-right (meaning a / b / c parses as (a / b) / c), the actual evaluation order of the left and right operands is unsequenced.

Evaluation Mechanics

The behavior of the / operator is strictly dictated by the data types of its operands: 1. Integer Division If both operands are of integer types, the operator performs integer division. The result is the algebraic quotient with any fractional part discarded. C++11 and later guarantee that this truncation is always directed towards zero.
2. Floating-Point Division If at least one operand is a floating-point type (float, double, long double), the operator performs floating-point division, preserving the fractional component up to the precision limits of the type.
3. Type Conversion When operands are of mixed types, the compiler applies usual arithmetic conversions to yield a common type before the operation. Integral promotions are applied first (e.g., short to int). If the types still differ, the compiler applies conversions based on type categories (e.g., converting an integer to a floating-point type) and signedness rules.

Undefined Behavior (UB)

The / operator introduces specific edge cases that result in Undefined Behavior:
  • Division by Zero (Integer): If the second operand evaluates to 0 and both operands are integers, the behavior is undefined. It typically results in a hardware exception (e.g., SIGFPE).
  • Division by Zero (Floating-Point): If the environment strictly adheres to IEEE 754, dividing a non-zero float by 0.0 yields ±Infinity, and 0.0 / 0.0 yields NaN (Not a Number). If IEEE 754 is not supported, it may invoke UB.
  • Signed Integer Overflow: Dividing the minimum representable value of a signed integer type by -1 results in UB. In a two’s complement system, the absolute value of INT_MIN is one greater than INT_MAX, meaning the positive result cannot be represented in the target type.

Operator Overloading

The / operator can be overloaded for user-defined types (classes, structs, or enumerations). It is conventionally implemented as a non-member function to allow symmetric implicit conversions on both the left-hand and right-hand sides. To achieve this symmetry, the user-defined type must provide an implicit converting constructor, and the operator must accept two objects of that type.
When overloading /, it is standard practice to also overload the compound assignment operator /= as a member function, and then implement the binary / operator in terms of /=.
Tired of Poor C++ Skills? Fix That With Deep Grasping!Learn More