Reputation: 96541
The C++ Primer says:
We can independently specify the signedees and the size of an integral literal. If the suffix contains a U, then the literal has an unsigned type, so a decimal, octal or hexadecimal literal with a U suffix has the smallest type of unsigned int, unsigned long or unsigned long long in which the literal's value fits
When one declares
int i = -12U;
The way i understand it is that -12 is converted to the unsigned
version of itself (4294967284
) and then assigned to an int
, making the result a very large positive number due to rollover.
This does not seem to happen. What am i missing please?
cout << i << endl; // -12
Upvotes: 2
Views: 1378
Reputation: 76523
12
has type int and the value 12.
12U
has type unsigned int and the value 12.
-12U
has type unsigned int and the value std::numeric_limits<unsigned int>::max()
+ 1 - 12.
int i = -12U;
applies an implementation-defined conversion to convert -12U to type int.
Upvotes: 1
Reputation: 64308
You are assigning the unsigned int back to a signed int, so it gets converted again.
It's like you did this:
int i = (int)(unsigned int)(-12);
Upvotes: 4
Reputation: 112424
u
effectively binds more tightly than -
. You are getting -(12u)
.
Upvotes: 2