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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With