Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

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).
auto result = lhs % rhs;

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

#include <iostream>
#include <climits>

int main() {
    // Standard evaluation
    int a = 10 % 3;  // Evaluates to 1
    int b = 10 % 5;  // Evaluates to 0
    
    // Sign semantics (Sign matches the left-hand operand)
    int c =  10 %  3; // Evaluates to  1
    int d = -10 %  3; // Evaluates to -1
    int e =  10 % -3; // Evaluates to  1
    int f = -10 % -3; // Evaluates to -1

    // Type promotion
    int   x = 10;
    long  y = 3L;
    auto  z = x % y;  // Evaluates to 1L. Type of z is 'long'
    
    // Compilation Error: Invalid operands
    // double err = 10.5 % 2.0; 
    
    // Undefined Behavior
    // int ub1 = 10 % 0; 
    // int ub2 = INT_MIN % -1;

    return 0;
}

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.
int val = 10;
val %= 3; // val is now 1
Master C++ with Deep Grasping Methodology!Learn More