Register    Login    Forum    Search    FAQ

Board index » Everything

Post new topic Reply to topic  [ 1 post ] 
Author Message
 Post Posted: May 12th, 2017, 3:40 pm 

Joined: February 28th, 2013, 3:23 am
Posts: 2480
Location: Oklahoma, United States
For anyone wondering how to get rid of red lines or VS2017 complaining about the Colors::MakeRGB function, I have a solution.

   static constexpr Color MakeRGB( unsigned int r,unsigned int g,unsigned int b )
      return ( r << 16u ) | ( g << 8u ) | b;

The original had some mixing of types and implicit conversions.
   static constexpr Color MakeRGB( unsigned char r, unsigned char g, unsigned char b )
      return ( r << 16 ) | ( g << 8 ) | b;

First, the parameters are of type unsigned char, limit is 255. The values passed in as constants in Colors are 255u for instance which is (unsigned int)255, so there is a conversion from unsigned int to unsigned char.
The operator<< bit shifting inside the function are int based since the literals aren't postfixed with the letter 'u', so depending on the promotion rule here (r, g, and b are all unsigned, but are unsigned chars so I'm not sure if they get promoted to unsigned ints when doing operations with signed int ) there is another implicit conversion either to signed or unsigned int.

Not sure about anyone else, but VS2017 seems to want to promote to int as the intellisense message I get is "Value exceeds range of (int)".

The only benefit to having the parameters as unsigned char would be to let programmers know that the max acceptable value is 255. However, this isn't necessarily enforced as the compiler would probably truncate passed in values over 255 causing a value of say 256 to end up as 0, 257 as 1 and so on. Changing the parameters to unsigned int isn't clear that the values passed in need to be between 0u and 255u, but it makes the compiler happy. A solution would be to use asserts
assert(r <= 255u);
assert(g <= 255u);
assert(b <= 255u);

If you think paging some data from disk into RAM is slow, try paging it into a simian cerebrum over a pair of optical nerves. -

Reply with quote  
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 1 post ] 

Board index » Everything

You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Search for: