U suffix in the variable declaration

825 views Asked by At

I know that if the number is followed with U suffix it is treated as unsigned. But why following program prints correct value of variable i even though it is initialized with negative value. (Compiled with gcc 4.9.2, 4.8.2, & 4.7.1)

Program1.cpp

#include <iostream>
int main()
{
    int i=-5U;
    std::cout<<i;  // prints -5 on gcc 4.9.2, 4.8.2, & 4.7.1
}

Program2.cpp

#include <iostream>
int main()
{
    auto i=-5U;
    std::cout<<i;  // prints large positive number as output
}

But If I use auto keyword (The type deducer new C++0x feature) it gives me large positive number as expected.

Please correct me If I am understanding incorrect something.

1

There are 1 answers

3
Sneftel On BEST ANSWER

-5U is not -5 U. It is -(5U). The minus sign is a negation operator operating on 5U, not the first character of an integer literal.

When you negate an unsigned number, it is equivalent to subtracting the current value from 2^n, where n is the number of bits in the integer type. So that explains the second program. As for the first, when you cast an unsigned integer to a signed integer (as you are doing by assigning it to an int), if the value is out of range the result is undefined behavior but in general* will result in the value being reinterpreted as an unsigned integer-- and since unsigned negation just so happens to have the same behavior as two's complement signed negation, the result is the same as if the negation happened in a signed context.

.* Note: This is NOT one of those "undefined behavior" situations that is only of academic concern to language wonks. Compilers can and do assume that casting an unsigned number to signed will not result in overflow (particularly when the resulting integer is then used in a loop), and there are known instances of this assumption turning carelessly written code into buggy programs.