truncation of constant value

Started by
4 comments, last by Inmate2993 19 years, 3 months ago
I'm not sure why this is happening but it seems that any constant value over 127 can't be passed to a char parameter without giving me a truncation error. ex:

	cMaterial::cMaterial()
	{
		// Set a default material (white)
		ZeroMemory(&m_material, sizeof(D3DMATERIAL9));
		SetDiffuseColor(255,255,255); // Line 3 truncation errors
	}

	bool cMaterial::SetDiffuseColor(char Red, char Green, char Blue)
	{
		m_material.Diffuse.r = 1.0f / 255.0f * (float)Red;
		m_material.Diffuse.g = 1.0f / 255.0f * (float)Green;
		m_material.Diffuse.b = 1.0f / 255.0f * (float)Blue;

		return true;
	}


error: c:\Documents and Settings\Dave\My Documents\Lyradis\include\cGraphics.cpp(639) : warning C4309: 'argument' : truncation of constant value c:\Documents and Settings\Dave\My Documents\Lyradis\include\cGraphics.cpp(639) : warning C4309: 'argument' : truncation of constant value c:\Documents and Settings\Dave\My Documents\Lyradis\include\cGraphics.cpp(639) : warning C4309: 'argument' : truncation of constant value Any ideas why it's doing this?
Advertisement
the problem is there are too few bits in a char (1 for sign, and 7 for the number). You can use *unsigned* chars which will let you go from 0 to 255.

bool cMaterial::SetDiffuseColor(unsigned char Red, unsigned char Green, unsigned char Blue)
It might be thinking char is signed, which would mean its range is from -128 to 127. unsigned char should work as expected.

@Onemind: Negative numbers are two's complement, not sign + number.
Ra
It is worth noting that in C++, the signedness of a char is implementation defined: char, signed char, and unsigned char are three distinct types.
Ah yes, I forgot about that. Thanks.
It'd probably be safer and faster to use ints and perform the truncation yourself.

See, int is by convention defined as the natural size of a "word" on a given arcitecture. I know technically its just char <= short <= int <= long, but the general convention is int is 32 bits signed. Anyways, when you work in ints, everything speeds up by a bit, since the code doesn't have to go truncating everything all over the place.
william bubel

This topic is closed to new replies.

Advertisement