TheDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
% 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
lhsis positive, the result is positive or zero. - If
lhsis negative, the result is negative or zero.
% operator can invoke undefined behavior (UB) in two specific scenarios:
- Division by Zero: If the right-hand operand (
rhs) evaluates to0. - Signed Integer Overflow: If the quotient of
lhs / rhsis not representable in the result type, the behavior of bothlhs / rhsandlhs % rhsis 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.
Master C++ with Deep Grasping Methodology!Learn More





