Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I've encountered code that performs the following conversion:

static_cast<unsigned long>(-1)

As far as I can tell, the C++ standard defines what happens when converting a signed integer value to an unsigned integral type (see: What happens if I assign a negative value to an unsigned variable?).

The concern I have in the above code is that the source and destination types may be different sizes and whether or not this has an impact on the result. Would the compiler enlarge the source value type before casting? Would it instead cast to an unsigned integer of the same size and then enlarge that? Or perhaps something else?

To clarify with code,

int nInt = -1;
long nLong = -1; // assume sizeof(long) > sizeof(int)

unsigned long res1 = static_cast<unsigned long>(nInt)
unsigned long res2 = static_cast<unsigned long>(nLong);

assert(res1 == res2); // ???

Basically, should I be worrying about writing code like

static_cast<unsigned long>(-1L)

over

static_cast<unsigned long>(-1)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
317 views
Welcome To Ask or Share your Answers For Others

1 Answer

From the C++11 standard, 4.7 "Integral conversions", para 2:

If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2n where n is the number of bits used to represent the unsigned type).

In other words, when converting to an unsigned integer, only the value of the input matters, not its type. Converting -1 to an n-bit unsigned integer will always give you 2n-1, regardless of which integer type the -1 started as.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...