"Bingfeng Mei" <b...@broadcom.com> writes: > #define A 255 > > int tst1(short a, short b){ > if(a > (b - A)) > return 0; > else > return 1; > > } > > > int tst2(short a, short b){ > short c = b - A; > if(a > c) > return 0; > else > return 1; > > }
These computations are different. Assume short is 16 bits and int is 32 bits. Consider the case of b == 0x8000. The tst1 function will sign extend that to 0xffff8000, subtract 255, sign extend a to int, and compare the sign extended a with 0xffff7f01. The tst2 function will compute 0x8000 - 255 as a 16 bit value, getting 0x7f01. It will sign extend that to 0x7f01, and compare the sign extended a with 0x7f01. It may seem that there is an undefined signed overflow when using this value, but there actually isn't. All computations in C are done in type int. So the computations have no overflow. The truncation from int to short is not undefined, it is implementation defined. Ian