Jump to content
  • Advertisement
Sign in to follow this  
Red Ant

[C++] static_cast'ing a negative value to an unsigned int

This topic is 3335 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Is the result of following line
const unsigned int a = static_cast < unsigned int > ( -1 );

well defined? I.e. does the standard make any guarantees as to what the outcome will be, or does this invoke undefined behavior? I've scanned the C++ standard for a clear statement on this matter but couldn't find anything.

Share this post


Link to post
Share on other sites
Advertisement
I don't know whether it's well defined, but the only behavior I've ever seen from compilers is to simply reinterpret the bits in that case. Since -1 is 0xFFFFFFFF in two's complement, casting it to an unsigned int results in 4,294,967,295.

Share this post


Link to post
Share on other sites
Section 4.7 paragraph 2, of ye holy standard:
Quote:

If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (module 2n where n is the number of bits used to represent the unsigned type). [Note: In a two's complement representation, this conversion is conceptual and there is no change in the bit pattern (if there is no truncation). ]

Share this post


Link to post
Share on other sites
Quote:
Original post by SiCrane
Section 4.7 paragraph 2, of ye holy standard:
Quote:

If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (module 2n where n is the number of bits used to represent the unsigned type). [Note: In a two's complement representation, this conversion is conceptual and there is no change in the bit pattern (if there is no truncation). ]


Wow, I'm actually kind of impressed that you get that guarantee.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!