typestar

Limits and overflow in C

Every integer type has a range, and crossing it is either wrapping or undefined.

#include <limits.h>
#include <stdio.h>

int safe_add(int a, int b, int *out) {
    if (b > 0 && a > INT_MAX - b) {
        return 0;
    }
    if (b < 0 && a < INT_MIN - b) {
        return 0;
    }
    *out = a + b;
    return 1;
}

void limits(void) {
    printf("int %d..%d\n", INT_MIN, INT_MAX);
    printf("unsigned max %u\n", UINT_MAX);

    unsigned char wraps = 255;
    wraps++;
    printf("wrapped to %u\n", wraps);

    int result = 0;
    printf("%d\n", safe_add(INT_MAX, 1, &result));
}

How it works

  1. <limits.h> names the bounds of each type.
  2. Unsigned arithmetic wraps; signed overflow is undefined behavior.
  3. Check before adding rather than after.

Keywords and builtins used here

The run, in numbers

Lines
25
Characters to type
431
Tokens
139
Three-star pace
80 tpm

At the three-star pace of 80 tokens a minute, this run takes about 104 seconds.

Type this snippet

Step 6 of 7 in Variables & types, step 6 of 35 in Language basics.

← Previous Next →