Skip to main content
The % operator is the built-in arithmetic remainder operator in C++. It evaluates to the remainder of the division of the left-hand operand (dividend) by the right-hand operand (divisor).

Operand Constraints

Strictly, both operands must be of integral types (e.g., int, char, long, unsigned) or unscoped enumeration types. Attempting to use the % operator with floating-point types (float, double) will result in a compilation error. Floating-point remainders require the <cmath> library function std::fmod.

Evaluation Rules and Mechanics

1. Standard Arithmetic Conversions Before the operation is performed, C++ applies standard arithmetic conversions to the operands to determine a common type. The result of the % operation is returned as this common type. 2. Sign Semantics (C++11 and later) Since C++11, integer division is strictly defined to truncate towards zero. Because the language guarantees the algebraic identity (a / b) * b + a % b == a, the sign of the remainder is strictly determined by the sign of the dividend (lhs). The sign of the divisor (rhs) has no effect on the sign of the result.
  • If lhs is positive, the result is positive or zero.
  • If lhs is negative, the result is negative or zero.
3. Undefined Behavior The % operator can invoke undefined behavior (UB) in two specific scenarios:
  • Division by Zero: If the right-hand operand (rhs) evaluates to 0.
  • Signed Integer Overflow: If the quotient of lhs / rhs is not representable in the result type, the behavior of both lhs / rhs and lhs % rhs is undefined. Consequently, evaluating the minimum representable value of any signed integer type modulo -1 (e.g., INT_MIN % -1) results in undefined behavior due to signed integer overflow.

Syntax and Behavior Visualization

Compound Assignment

The % operator can be combined with the assignment operator as %=. The expression a %= b is semantically equivalent to a = a % b, except that the operand a is evaluated only once.
Tired of Poor C++ Skills? Fix That With Deep Grasping!Learn More