CKTIS / C++
Subtraction operator and unary minus
The symbol `-` means subtraction in `a - b` and arithmetic negation in `-x`. It can also move a pointer or calculate the distance between pointers. Correct results depend on type conversions, numeric ranges, and array boundaries.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
a - b
-x
p - n
p - qBinary a - b subtracts b from a; arithmetic operands first undergo the usual arithmetic conversions. a - b - c means (a - b) - c. Unary -x computes the negative value after integral promotions. Using these built-in operators does not itself modify their operands.
The result type matters: unsigned arithmetic operates modulo 2^N, where N is the type's width. Mixing signed and unsigned types can therefore produce surprising results. Signed integer overflow is undefined behavior; this also applies to negating a type's minimum value if promotion does not change the type.
For suitable pointers, p - n moves a pointer by n elements, staying within the same array or one past it. In C++23, if p is a null pointer and n is zero, p - n yields a null pointer. p - q produces an element distance of type std::ptrdiff_t: the pointers must belong to the same array, allowing the one-past position, and the result must be representable. Subtracting two null pointers yields zero. A one-past pointer must not be dereferenced.
The example demonstrates both numeric forms and both pointer forms. Expected output is 7, -5, 40, 4, each on its own line. The supplied source is an evolving draft, not a frozen C++23 edition.
Examples
#include <iostream>
int main() {
int a = 12;
int b = 5;
int values[] = {10, 20, 30, 40};
int* end = values + 4;
std::cout << a - b << '\n';
std::cout << -b << '\n';
std::cout << *(end - 1) << '\n';
std::cout << end - values << '\n';
}
Result
7 -5 40 4
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.