unsigned policy

torhu fake at address.dude
Wed Feb 7 13:25:33 PST 2007


orgoton wrote:
> I always use unsigned variables when their values don't go below 0. I also always use the smallest variable possible.
> 
> More often than not, I use "ubyte" instead of "int" in "for" loops. Signed variables use the most significant bit to represent sign. I don't know if there's any performance gain (even if marginal) when using mathematical operations on unsigned variables.

Using the smallest variable type possible doesn't gain you anything. 
It's common to use int in most cases, or size_t for indices.  Smaller 
types are generally used to save space for strings, structs that you 
have large arrays of, etc.

int and other 32-bit types are generally the fastest type for a 32-bit 
cpu to work with.  Except when copying arrays of data around, that's 
when it can be faster to use smaller types. Not for individual variables.

> About conditions, you can always force a variable to be unsigned by masking away it's most significant bit:
> 
> short var2;
> (...)
> unsigned=var2 && 0x3FFF; (0x3FFF is hexadecimal for 0111_1111_1111_1111)
 >

I think this is what you mean:
ushort var3 = var2 & 0x7FFF;

But this doesn't make the variable unsigned.  Signed or unsigned is not 
a quality of the value, it's a matter of how a value is interpreted and 
treated by the compiler/cpu/library.

Look at this:

uint x = -1;

If you print x, you will se that it's 4294967295, since -1 is 0xFFFFFFFF.



More information about the Digitalmars-d mailing list