This is the mail archive of the
gcc@gcc.gnu.org
mailing list for the GCC project.
Re: why GCC does implicit promotion to unsigned char?
- From: Jakub Jelinek <jakub at redhat dot com>
- To: Konstantin Vladimirov <konstantin dot vladimirov at gmail dot com>
- Cc: gcc at gcc dot gnu dot org
- Date: Thu, 26 Jan 2012 12:04:15 +0100
- Subject: Re: why GCC does implicit promotion to unsigned char?
- References: <CADn89gTkDC2JsU1wjBpMagSRtjGS_dq=jKGTBjG2tT6qS5bzrg@mail.gmail.com>
- Reply-to: Jakub Jelinek <jakub at redhat dot com>
On Thu, Jan 26, 2012 at 02:27:45PM +0400, Konstantin Vladimirov wrote:
> Consider code:
>
> char A;
> char B;
>
> char sum_A_B ( void )
> {
> char sum = A + B;
>
> return sum;
> }
> [repro.c : 6:8] A.0 = A;
> [repro.c : 6:8] A.1 = (unsigned char) A.0;
> [repro.c : 6:8] B.2 = B;
> [repro.c : 6:8] B.3 = (unsigned char) B.2;
> [repro.c : 6:8] D.1990 = A.1 + B.3;
> [repro.c : 6:8] sum = (char) D.1990;
> [repro.c : 8:3] D.1991 = sum;
> [repro.c : 8:3] return D.1991;
> }
>
> It looks really weird. Why gcc promotes char to unsigned char internally?
To avoid triggering undefined behavior.
A + B in C for char A and B is (int) A + (int) B, so either we'd have to
promote it to int and then demote, or we just cast it to unsigned and do the
addition in 8-bit. If we don't do that, e.g. for
A = 127 and B = 127 we'd trigger undefined behavior of signed addition.
In unsigned char 127 + 127 is valid.
Jakub