Re: signed/unsigned warnings
On Feb 10, 12:52 pm, SG <s.gesem...@gmail.com> wrote:
On 10 Feb., 10:57, perses wrote:
I am using VS 2005.
The following code generates a warning :
unsigned int ui = -1;
The following don't :
int a = -1;
unsigned int tempui = a;
int b = ui;
Could someone explain please/
Since the conversion from some (possibly signed) integer to an
unsigned integer is well-defined (*), each of the code
fragments may rely on this behaviour and intentionally use
this implicit conversion in which case there is no error.
Obviously, the Microsoft Compiler considers the chance of
a programming error in the first example to be higher than the
chance of error in the second one. But the reason for this is
beyond me.
In fact, you could almost justify a warning in the second case.
In the first case, the alternatives are:
unsigned int ui = UINT_MAX;
unsigned int ui = std::numeric_limits<unsigned int>::max();
unsigned int ui = -1;
The first two require changing the initializer if you change the
type to, say, unsigned long. The last works correctly for all
unsigned types.
If the compiler authors insist on the warning, they should at
least inhibit it when the initializer is a constant -1; that's
*the* standard idiom for initializing unsigned values to their
maximum.
--
James Kanze