Overflow

There are a number of data types in C that can hold numbers. The integer-types have a maximum and minimum value and if we increment the variable beyond the maximum value it will become the minimum possible value. That is MAX+1 will become MIN. This is called integer overflow.

The same is true if we decrement beyond the minimal value. So MIN-1 will become MAX. This is called underflow.

Let's see a few examples with some of the data types.

char

#include<stdio.h>


int main() {
    char c;

    c = '~';
    printf("%i %c\n", c, c);

    c++;
    printf("%i %c\n", c, c);

    c++;
    printf("%i\n", c); // This will print -128 and the character is unprintable

    return 0;
}
126 ~
127 
-128

int

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

int main() {
    int num;

    num = INT_MAX;
    printf("%i\n", num);

    num++;
    printf("%i\n", num);
    
    return 0;
}
2147483647
-2147483648