Visual Studio 2017 and MakeRGB()

The Partridge Family were neither partridges nor a family. Discuss.
Post Reply
albinopapa
Posts: 4373
Joined: February 28th, 2013, 3:23 am
Location: Oklahoma, United States

Visual Studio 2017 and MakeRGB()

Post by albinopapa » May 12th, 2017, 3:40 pm

For anyone wondering how to get rid of red lines or VS2017 complaining about the Colors::MakeRGB function, I have a solution.

Code: Select all

	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.

Code: Select all

	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

Code: Select all

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. - gameprogrammingpatterns.com

Post Reply