CKTIS / C++
Remainder operator %
The built-in % operator computes the remainder of integer division. It is not a percentage operator or a guarantee of nonnegative modulo: a nonzero remainder has the sign of the dividend after type conversions. A zero divisor or an unrepresentable quotient causes undefined behavior.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
a % bThe built-in operator a % b returns the remainder of dividing a by b. It accepts integral types and unscoped enumerations, not floating-point types. The usual arithmetic conversions determine the common operand type and result type. Mixing signed and unsigned types can therefore change how a negative value is interpreted.
Integer division discards the fractional part toward zero. For valid operands, (a / b) * b + a % b == a holds. A nonzero remainder has the sign of the converted dividend: -17 % 5 gives -2, while 17 % -5 gives 2. This is therefore not always nonnegative modulo.
Warning: b == 0 causes undefined behavior. So does a quotient that cannot fit in the result type, for example INT_MIN % -1 with int operands, even though the mathematical remainder is zero.
The test a % b == 0 checks divisibility, provided the operation is valid. The operators %, *, and / have equal precedence and group left-to-right. This description concerns the built-in operator; an overload for a user-defined type may have different meaning.
Examples
#include <iostream>
int main() {
std::cout << 17 % 5 << '\n';
std::cout << -17 % 5 << '\n';
std::cout << 17 % -5 << '\n';
std::cout << (18 % 3 == 0) << '\n';
}
Result
2 -2 2 1
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.