QP School
Overflow and underflow with short int in C - Printable Version

+- QP School (https://qomplainerzschool.lima-city.de)
+-- Forum: Tutorials (https://qomplainerzschool.lima-city.de/forumdisplay.php?fid=3)
+--- Forum: C 18 Tutorials (https://qomplainerzschool.lima-city.de/forumdisplay.php?fid=32)
+--- Thread: Overflow and underflow with short int in C (/showthread.php?tid=5148)



Overflow and underflow with short int in C - Qomplainerz - 07-26-2023

Example:

#include <stdio.h>

int main() {
    short int max = 32767;
    short int min = -32768;

    // Overflow example
    short int overflowed = max + 1;
    printf("Overflowed value: %d\n", overflowed);

    // Underflow example
    short int underflowed = min - 1;
    printf("Underflowed value: %d\n", underflowed);

    return 0;
}

Explanation:

In this example, we demonstrate what happens when a short int variable encounters overflow and underflow. The max value for a short int is 32767, and adding 1 to it causes an overflow, resulting in a value of -32768, which is the min value for a short int. Similarly, subtracting 1 from the min value causes an underflow, resulting in 32767, which is the max value for a short int.