Possible Maths bug? uint32 < 0....

Hi, I was noticing some weird behaviour in my code using uint32. When I did an if check to see if it was < 0, it always returned false, even if it’s value was negative. I produced a simple test code snippet as follows:



	// Create
	uint32 testValue1 = 3000;
	// Deplete
	testValue1-= 5000;

	// Check if less than 0
	if ( testValue1 < 0 )
	{
		debugLog( "testvalue1 IS LESS THAN 0... val=" + FString::FromInt( testValue1 ) );
	}
	else
	{
		debugLog( "testvalue1 IS GREATER THAN 0... val=" + FString::FromInt( testValue1 ) );
	}


For some bizarre reason this results in the if check failing, even though testValue1 is equal to -2000. What on earth is going on?

Unsigned ints cannot hold a negative value, afaik.

Have a look at this, it will explain why this is happening: Data Type Ranges | Microsoft Docs

The ‘u’ in ‘uint’, ‘uint8’, ‘uint32’ etc means that it’s unsigned.

Unsigned means that the integer has no ‘sign’, which basically means it’s always positive. If you try and take the value below 0, then the value will just wrap round to the maximum value (so 0-2000 will actually be the maximum possible value the integer can hold, minus 2000. Therefore it’s a positive value).

If you’re wondering why you’d ever use an unsigned integer, it’s because you don’t have to reserve bits for the signing of the number you can contain a much larger maximum value. Example cases are for highscores / counters etc which will never be a negative value but could grow to be quite large.

Use int32 instead, if you want it to store negative values.