Course contentsShow
← C
Lesson 157 of 1,2193. Operators and ExpressionsFree lesson

Basic arithmetic overflow

Basic arithmetic overflow

What you'll learn: Why numbers in C can suddenly turn negative or wrap around when they get too large for their data type.

The Odometer Effect

Imagine the mechanical odometer in an old car that only has five digits. When you drive the mile that takes you past 99,999, the display doesn't show 100,000—it simply rolls back to 00,000. C variables work exactly like this.

Every data type in C, such as an int or a char, has a fixed amount of physical space in memory. Because space is limited, there is a maximum value each type can hold. When you try to add 1 to a variable that is already at its limit, it "overflows," spilling over and wrapping back to the beginning of its range.

Signed Integer Wrap-around

In C, most integers are "signed," meaning they use one bit of their memory to track whether the number is positive or negative. Because of how computers handle binary math, when a signed integer hits its maximum positive limit and you add more to it, it wraps around into the most negative possible value.

Think of it like a circular clock face where the top is the maximum positive number and the bottom is the maximum negative number. If you keep moving clockwise, you eventually cross the line from "very positive" to "very negative."

Seeing it in Action

In the example below, we use a signed char. A typical char can only hold values from -128 to 127. Watch what happens when we push it past 127:

#include <stdio.h>

int main() {
    // A char is a small integer usually maxing at 127
    signed char myNumber = 127;
    
    printf("Starting value: %d\n", myNumber);
    
    // Adding 1 to the maximum possible value
    myNumber = myNumber + 1;
    
    printf("After adding 1: %d\n", myNumber);
    
    return 0;
}

If you run this, the output won't be 128. Instead, it will be -128. The number hit the ceiling and shattered through to the floor.

Why This Matters

Arithmetic overflow is a common source of bugs. If you are calculating the number of pixels in a high-resolution image or the balance of a bank account, exceeding the limit of an int could cause your program to suddenly treat a large positive result as a massive negative one, leading to crashes or incorrect logic.

Key takeaway

Arithmetic overflow occurs when a calculation exceeds a data type's capacity, causing the value to "wrap around" to the opposite end of its range.