This is the mail archive of the
gcc@gcc.gnu.org
mailing list for the GCC project.
Re: Why are these two functions compiled differently?
- From: Ian Lance Taylor <iant at google dot com>
- To: "Bingfeng Mei" <bmei at broadcom dot com>
- Cc: "gcc\ at gcc dot gnu dot org" <gcc at gcc dot gnu dot org>, "John Redford" <jredford at broadcom dot com>
- Date: Tue, 03 Mar 2009 07:47:15 -0800
- Subject: Re: Why are these two functions compiled differently?
- References: <7FB04A5C213E9943A72EE127DB74F0AD49F007DD90@SJEXCHCCR02.corp.ad.broadcom.com>
"Bingfeng Mei" <bmei@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