CKTIS / C
Integer negation in C: promotions and limits
After any applicable integer promotions, unary minus on a signed integer gives the arithmetic opposite if that value is representable in the promoted type; otherwise the behavior is undefined. For an unsigned promoted type, the result is computed modulo one more than the type’s maximum.
Version: ISO C23; implementation support may vary
Syntax
- cast-expression
Examples: -x, -(a + b), -1, (size_t)-1Unary negation is another name for unary minus (-x), not a separate operator. This note focuses on applying unary minus to integers. Do not confuse it with logical negation (!x).
Applicable integer promotions happen first, and the promoted type is the result type. For example, short promotes to int, while a C23 _BitInt operand that is not a bit-field is exempt. If the promoted type is unsigned, the result is computed modulo that type's maximum plus one: -1u gives UINT_MAX. In (size_t)-1, the negation first produces the int value -1; converting it to size_t gives SIZE_MAX.
In C23 the opposite of INT_MIN cannot be represented in int, so evaluating -x when an int x holds INT_MIN has undefined behavior. Check x != INT_MIN before negating. Casting the result, as in (long long)-x, does not prevent the overflow. C23 support varies by implementation.
Use -1 as an error or not-found result only if the function's contract defines it that way; do not store it in an unsigned type if it must remain negative. Reserve SIZE_MAX as a sentinel only if it cannot be a valid result. In an int comparator, use a < b and a > b instead of returning a - b: the difference can overflow at the extremes.
Examples
#include <limits.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
static int compare_ints(int a, int b)
{
return a < b ? -1 : (a > b ? 1 : 0);
}
int main(void)
{
short n = 7;
int x = INT_MIN;
size_t missing = (size_t)-1;
printf("-n = %d\n", -n);
printf("-1u == UINT_MAX: %d\n", -1u == UINT_MAX);
printf("missing == SIZE_MAX: %d\n", missing == SIZE_MAX);
printf("compare(INT_MIN, INT_MAX) = %d\n", compare_ints(x, INT_MAX));
if (x == INT_MIN) {
puts("INT_MIN: negation skipped");
} else {
printf("-x = %d\n", -x);
}
return 0;
}
Result
-n = -7 -1u == UINT_MAX: 1 missing == SIZE_MAX: 1 compare(INT_MIN, INT_MAX) = -1 INT_MIN: negation skipped
The program shows `short` promotion, both unsigned equalities, and comparison at the `int` limits. The guard prevents evaluation of the negation of `INT_MIN`.
Related lessons
- C · Lesson 63 · Advanced · Version: 3
- C · Lesson 64 · Advanced · Version: 3
- C · Lesson 65 · Advanced · Version: 3
- C · Lesson 67 · Advanced · Version: 3
- C · Lesson 70 · Advanced · Version: 3
- C · Lesson 71 · Advanced · Version: 3
- C · Lesson 72 · Advanced · Version: 3
- C · Lesson 76 · Advanced · Version: 3
- C · Lesson 80 · Advanced · Version: 3
- C · Lesson 81 · Advanced · Version: 3