Re: Confusion about integer promotions.
- From: "BigMan" <fn42551@xxxxxxxxxxxxxxxx>
- Date: Mon, 13 Jun 2005 12:47:33 +0300
"John Carson" <jcarson_n_o_sp_am_@xxxxxxxxxxxxxxx> wrote in message
news:OiWrMp$bFHA.3184@xxxxxxxxxxxxxxxxxxxxxxx
> "BigMan" <fn42551@xxxxxxxxxxxxxxxx> wrote in message
> news:OHANMG$bFHA.2984@xxxxxxxxxxxxxxxxxxxx
>> Let's consider this piece of code:
>>
>> unsigned short A = 0;
>> unsigned int B = 0;
>> signed int C = 0;
>>
>> // For each of these line, should A be promoted to int or to unsigned
>> int according to the C++ standard if an int can represent all the
>> values of an unsigned short?
>>
>> bool d = A < B;
>> bool e = A < C;
>
> Section 4.5/1 of the C++ standard:
>
> "An rvalue of type char, signed char, unsigned char, short int, or
> unsigned short int can be converted to an rvalue of type int if int can
> represent all the values of the source type; otherwise, the source rvalue
> can be converted to an rvalue of type unsigned int."
>
> i.e., promotion is always to the signed version if it is large enough,
> otherwise to the unsigned version.
>
> Mixing signed and unsigned integers is very hazardous. I have been bitten
> by it more than once and avoid such situations if at all possible.
>
> --
> John Carson
First, signed int is large enough on x86 (4 bytes) to hold all values of an
unsigned short (2 bytes), so values of the latter type should be promoted to
signed int and not to unsigned int. But VC++.NET seem to promote unsigned
short either to signed int or to unsigned int regardless of what 4.5/1 says,
since it does not issue a singed/unsigned mismatch warning when compiling
the above code with the /W4 switch (highest warning level). Is this
non-conformant behaviour or what?
Second, using only unsigned integers (but of different types) is also
hazardous, since an unsigned short or unsigned char may be promoted to
signed int, which again leads to mixing signed and unsigned integers.
Probably, a more generic rule should read something like: "Do not mix
integers of different types", where signedness should also be taken into
account.
Could you, please, mention some of the problems you have come upon when
mixing signed and unsigned integers?
.
- Follow-Ups:
- Re: Confusion about integer promotions.
- From: John Carson
- Re: Confusion about integer promotions.
- References:
- Confusion about integer promotions.
- From: BigMan
- Re: Confusion about integer promotions.
- From: John Carson
- Confusion about integer promotions.
- Prev by Date: Re: Confusion about integer promotions.
- Next by Date: Rational Purify detects memory leaks in function SHFileOperation()
- Previous by thread: Re: Confusion about integer promotions.
- Next by thread: Re: Confusion about integer promotions.
- Index(es):
Relevant Pages
|