The use of unsigned int
Stephen Clamage
steve at taumet.com
Sun Feb 10 05:12:02 AEST 1991
paul at tredysvr.Tredydev.Unisys.COM (Paul Siu) writes:
>The most commonly use, and commonly returned type in C is probably int.
>In some cases, wouldn't it be more appropriate if unsigned int was used
>instead, such as when you are indexing an array, or returning a length?
>I heard that int is usually declared as the most efficent type in C, would
>using unsigned int cause any problems such as slow things down or cause
>type-conversation problems?
Using unsigned int won't generally speed things up (it might in selected
cases). The type of variable should be related to what it represents.
Unsigned types are useful for counters and sizes of things. If you
want the size of an object, use standard type size_t, which is an
unsigned type suitable to measure any object in the system.
With unsigned integer types you do have to be careful about comparisons
near the boundaries of the type and the corresponding signed type.
You can get unintended results:
1.
unsigned i;
for( i = 10; i >= 0; --i )
...
This loop will never terminate. An unsigned number can never be negative.
2.
unsigned u;
int i;
...
if( i < u )
...
In the comparison, i is converted to unsigned, then compared to u.
If i were initially negative, it might now look larger than u.
--
Steve Clamage, TauMetric Corp, steve at taumet.com
More information about the Comp.lang.c
mailing list