Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 135 ยท Variables and Types

Type Limits: limits.h and float.h

Find the exact range of every C type with limits.h, stdint.h and float.h - INT_MAX, CHAR_BIT, SIZE_MAX, DBL_EPSILON - and detect integer overflow safely, including C23 ckd_add.

How big can an int get on this machine? How many bits are in a byte? What's the smallest double greater than zero? C programs shouldn't guess these numbers, because they vary between platforms. Instead, the standard library publishes them as macros in three headers: <limits.h> for the standard integer types, <stdint.h> for the fixed-width and special-purpose types, and <float.h> for floating-point types.

Knowing the limits matters most for one job: preventing overflow. As you saw in Integer Types, signed overflow is undefined behavior, so you have to check before an operation whether its result will fit. This lesson lists the limit macros you'll actually use, then shows reliable ways to check additions, subtractions and multiplications, including the C23 checked-arithmetic functions ckd_add, ckd_sub and ckd_mul.

limits.h: the standard integer types

<limits.h> defines a minimum and maximum for each standard integer type. Unsigned types have no _MIN macro because their minimum is always 0.

Macro Meaning Value on our server
CHAR_BIT Bits in a byte (a char) 8
SCHAR_MIN, SCHAR_MAX signed char range โˆ’128, 127
UCHAR_MAX unsigned char maximum 255
CHAR_MIN, CHAR_MAX Plain char range (signed or unsigned, see Characters) โˆ’128, 127
SHRT_MIN, SHRT_MAX, USHRT_MAX short โˆ’32768, 32767, 65535
INT_MIN, INT_MAX, UINT_MAX int โˆ’2147483648, 2147483647, 4294967295
LONG_MIN, LONG_MAX, ULONG_MAX long ยฑ9.2 ร— 10ยนโธ, 1.8 ร— 10ยนโน
LLONG_MIN, LLONG_MAX, ULLONG_MAX long long same as long here
MB_LEN_MAX Maximum bytes in a multibyte character 16

C23 adds width macros that give the number of value bits directly: CHAR_WIDTH, INT_WIDTH, LONG_WIDTH, LLONG_WIDTH, BOOL_WIDTH and so on. They save you from computing sizeof(int) * CHAR_BIT, which also counts padding bits on exotic hardware.

C Printing the integer limits

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

These macros are constant expressions, so you can use them in #if directives and static_assert. A program that assumes a 32-bit int can make the assumption explicit and fail loudly at compile time on any machine where it's wrong:

C
#include <limits.h>

static_assert(INT_MAX >= 2147483647, "this program needs at least a 32-bit int");

#if LONG_MAX > INT_MAX
    /* long is wider than int on this platform */
#endif

static_assert is a keyword in C23; C11 spells it _Static_assert (or static_assert via <assert.h>). Predefined Macros and assert covers it in detail.

stdint.h: limits of the other integer types

The types from <stdint.h> have their own limit macros, named after the type in capitals:

Macro Meaning
INT8_MIN โ€ฆ INT64_MAX, UINT8_MAX โ€ฆ UINT64_MAX Exact-width types
INTMAX_MIN, INTMAX_MAX, UINTMAX_MAX Widest integer types
SIZE_MAX Largest size_t: the upper bound for any object size
PTRDIFF_MIN, PTRDIFF_MAX Range of ptrdiff_t, the type of a pointer difference
INTPTR_MAX, UINTPTR_MAX Pointer-sized integers

<stdint.h> also provides macros for writing constants of those types: INT64_C(5000000000) and UINT32_C(42) add whatever suffix the platform needs.

C Limits of size_t and fixed-width types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The specifiers %td (for ptrdiff_t) and %jd (for intmax_t) are less known siblings of %zu; they've been in printf since C99.

float.h: floating-point limits

<float.h> describes the range and precision of float, double and long double with the prefixes FLT_, DBL_ and LDBL_:

Macro (DBL_ version) Meaning
DBL_MAX Largest finite value
DBL_MIN Smallest positive normalized value
DBL_TRUE_MIN (C11) Smallest positive value at all (a subnormal)
DBL_EPSILON Difference between 1.0 and the next representable value
DBL_DIG Decimal digits that survive text โ†’ double โ†’ text
DBL_DECIMAL_DIG (C11) Digits needed so double โ†’ text โ†’ double is exact
DBL_MANT_DIG Bits in the significand (mantissa), including the hidden bit
DBL_MAX_EXP, DBL_MIN_EXP Binary exponent range
C Floating-point limits for all three types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

DBL_EPSILON is about 2.2 ร— 10โปยนโถ: adding it to 1.0 produces a different number, while adding half of it rounds back to 1.0. Epsilon describes precision near 1.0. Near 1,000,000 the gap between neighboring doubles is a million times larger, so don't use DBL_EPSILON as a universal tolerance for comparisons; use a relative one, as in Floating-Point Numbers.

Tip: To print a double so that reading it back gives exactly the same value, use DBL_DECIMAL_DIG (17) significant digits: printf("%.*g", DBL_DECIMAL_DIG, x). The * takes the precision from the next argument.

Detecting overflow before it happens

Because signed overflow is undefined, the check has to happen before the arithmetic and must not overflow itself. The trick is to rearrange the condition so that only safe operations happen. For a + b:

  • If b > 0, the sum overflows exactly when a > INT_MAX - b. Since b is positive, INT_MAX - b can't overflow.
  • If b < 0, the sum underflows exactly when a < INT_MIN - b.
C Safe addition and multiplication checks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The multiplication check divides instead of multiplying: a > INT_MAX / b asks the same question as a * b > INT_MAX but can't overflow. The sign cases are fiddly, and the last row shows why they matter: -1 * INT_MIN overflows, because +2147483648 doesn't fit in an int. That's also why abs(INT_MIN) and INT_MIN / -1 are undefined.

Unsigned arithmetic never has undefined behavior, but wrapping is usually still a bug. For unsigned values the checks are simpler: a + b wraps exactly when a > UINT_MAX - b, and after the fact, sum < a reliably detects a wrapped unsigned addition. A very common real case is computing an allocation size:

C
// Before malloc(count * size), make sure the multiplication can't wrap.
if (size != 0 && count > SIZE_MAX / size) {
    return NULL;   // the request is too large
}
void *block = malloc(count * size);

Checked arithmetic in C23: ckd_add, ckd_sub, ckd_mul

Writing those checks by hand is error-prone, so C23 standardized checked arithmetic in <stdckdint.h>. Each macro computes the mathematically exact result, stores it (wrapped to fit) through the pointer in the first argument, and returns true if the result didn't fit:

C
bool ckd_add(type1 *result, type2 a, type3 b);
bool ckd_sub(type1 *result, type2 a, type3 b);
bool ckd_mul(type1 *result, type2 a, type3 b);

The operands and result can be any integer types (not bool, char or enums), even different ones; the check is against the type of *result:

C C23 checked arithmetic

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Notice the last case: both operands are int, but because the result type is long long, the product is checked against long long and fits. That makes ckd_mul perfect for "compute in a wider type safely".

<stdckdint.h> needs a C23 compiler and library: GCC 14+ or Clang 18+. On older GCC and Clang versions, the compiler built-ins __builtin_add_overflow, __builtin_sub_overflow and __builtin_mul_overflow do the same job with the operands first and the result pointer last. They're extensions, so wrap them in a macro or function if you need portability to MSVC.

Don't test after the fact. int sum = a + b; if (sum < a) { ... } has undefined behavior at the addition, and GCC may remove the check entirely, as shown in Integer Types. Only unsigned addition can be checked afterwards.

Range-checking conversions

Limits are also the tool for safe narrowing (see Type Conversions). Before converting a long to an int, or a double to an int, check that the value is in range:

C
long big_value = get_value();
if (big_value < INT_MIN || big_value > INT_MAX) {
    fprintf(stderr, "value out of range for int\n");
} else {
    int value = (int)big_value;
    /* ... */
}

The same pattern appears when you parse numbers from text: strtol returns a long and reports overflow through errno, and then you check that result against INT_MIN/INT_MAX before storing it in an int. The Converting Strings and Numbers lesson builds a complete, safe parser.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which macro gives the number of bits in a byte?

    CHAR_BIT from limits.h is the number of bits in a char, which C defines as a byte. It's 8 on all mainstream hardware. (C23's UCHAR_WIDTH has the same value, but CHAR_BIT is the classic, portable answer.)
  2. 2. With int a and int b > 0, which condition safely detects that a + b would overflow?

    INT_MAX - b can't overflow when b is positive, so the comparison is always defined. The other tests evaluate the overflowing sum (undefined) or test the wrong thing.
  3. 3. int r; bool o = ckd_add(&r, INT_MAX, 1); What is o?

    ckd_add returns true when the exact result can't be represented in the type of *result. It never has undefined behavior; r receives the wrapped value INT_MIN.
  4. 4. What does DBL_EPSILON represent?

    DBL_EPSILON is the distance from 1.0 to the next representable double, about 2.2e-16. The smallest positive double is DBL_TRUE_MIN, and comparisons need a tolerance scaled to the values involved.
  5. 5. Why is -1 * INT_MIN undefined behavior with a 32-bit int?

    Two's complement ranges are asymmetric. INT_MIN is -2147483648, and its negation doesn't fit in an int, so the multiplication overflows. abs(INT_MIN) and INT_MIN / -1 have the same problem.

Summary

  • <limits.h> gives the range of every standard integer type (INT_MAX, LLONG_MIN, UCHAR_MAX, โ€ฆ) and CHAR_BIT; C23 adds width macros like INT_WIDTH.
  • <stdint.h> provides SIZE_MAX, PTRDIFF_MAX, INT64_MAX and friends, plus INT64_C() for constants.
  • <float.h> describes floating types: DBL_MAX, DBL_MIN, DBL_TRUE_MIN, DBL_EPSILON, DBL_DIG, DBL_DECIMAL_DIG.
  • Check for signed overflow before the operation with rearranged comparisons like a > INT_MAX - b, or divide instead of multiplying.
  • C23's ckd_add, ckd_sub and ckd_mul (GCC 14+, Clang 18+) compute and check in one step; __builtin_*_overflow is the older GCC/Clang extension.
  • Use the limits to range-check narrowing conversions and allocation sizes.

Next: typedef, where you'll learn to give types your own names.