【笔记】C 有符号整数溢出检测

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

int add(int a, int b)
{
    if((a >= 0 && INT_MAX - a < b) || (a < 0 && INT_MIN - a > b))
    {
        printf("Overflow\n");
        return -1;
    }
    else
        return a + b;
}

int main()
{
    int a = INT_MAX / 2;
    int b = a + 1;
    printf("%d + %d = %d", a, b, add(a, b));
    system("pause");
}

Protected: 自言自语

This content is password protected. To view it please enter your password below: