Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: Implicit casting and integer overflowing in the evaluation of expressions

Tags:

c

Let's take the code

int a, b, c;
...
if ((a + b) > C)

If we add the values of a and b and the sum exceeds the maximum value of an int, will the integrity of the comparison be compromised? I was thinking that there might be an implicit up cast or overflow bit check and that will be factored into the evaluation of this expression.

like image 256
lillq Avatar asked Feb 04 '26 22:02

lillq


2 Answers

C will do no such thing. It will silently overflow and lead to a possibly incorrect comparison. You can up-cast yourself, but it will not be done automatically.

like image 83
hazzen Avatar answered Feb 06 '26 12:02

hazzen


A test confirms that GCC 4.2.3 will simply compare with the overflowed result:

#include <stdio.h>

int main()
{
    int a, b, c;

    a = 2000000000;
    b = 2000000000;
    c = 2100000000;

    printf("%d + %d = %d\n", a, b, a+b);
    if ((a + b) > c)
    {
        printf("%d + %d > %d\n", a, b, c);
    }
    else
    {
        printf("%d + %d < %d\n", a, b, c);
    }
    return 0;
}

Displays the following:

2000000000 + 2000000000 = -294967296
2000000000 + 2000000000 < 2100000000
like image 44
Rob Pilkington Avatar answered Feb 06 '26 11:02

Rob Pilkington