Functions g1() and g2() have identical logic, but the input types have different sizes. Why do they return different results for negative sums?
/*BINFMTCXX: -Wall -Werror -Wextra -std=c++11
*/
#include <stdio.h>
#include <stdint.h>
char g1( int32_t a, uint32_t b ) { return a+b<9; } // fails when a+b is negative
char g2( int16_t a, uint16_t b ) { return a+b<9; } // works if no overflow
int main()
{
for ( int a=-2, b=0; a<=2; a++ )
{
fprintf(stderr,"a=%+d, b=%d, g1=%+d, g2=%+d %s\n", a, b, g1(a,b), g2(a,b), g1(a,b)==g2(a,b)?"":"!" );
}
return 0;
}
When I run it, it shows that g1() fails when a+b is negative:
$ ./mixed_sign_math_per_size.cpp
a=-2, b=0, g1=+0, g2=+1 !
a=-1, b=0, g1=+0, g2=+1 !
a=+0, b=0, g1=+1, g2=+1
a=+1, b=0, g1=+1, g2=+1
a=+2, b=0, g1=+1, g2=+1
The results are the same in C and C++.