Every time I've used the unsigned
keyword it has been before int
, or another built-in type. I was wondering if there were any other ways unsigned
could be used.
unsigned
keyword?unsigned
?If not, why does it have its own keyword? Why is unsigned int
not uint
?
The main question has been answered several times: the unsigned
keyword can only be used as a type-specifier for an integral type.
As for why unsigned
is a separate keyword, rather than having, say, a uint
keyword, the reasons for that are historical.
The earliest versions of C (pre-K&R) had only four fundamental types:
char
(8 bits, signed, 2's-complement)int
(16 bits, signed, 2's-complement)float
(32 bits)double
(64 bits, same range as float
but greater precision)Note what's missing: no signed
or unsigned
keywords, no short
, long
, or long double
; all those were added later. (Programmers who needed unsigned arithmetic commonly used pointers, which were freely interchangeable with int
.)
Each fundamental type had a name that was a single keyword, which made the grammar straightforward.
When other types were added later, it made sense to add specifiers like unsigned
, short
, and long
to the existing type names rather than introducing new keywords (which might have broken existing code). When the ANSI C committee standardized the language in 1989, they had to make a coherent structure out of the existing not-quite-formal definitions while remaining consistent with existing implementations. The result is what we have now, where int long unsigned long
is a valid type name (more commonly written as unsigned long long
).
If the language were being designed from scratch now, I suspect that a different approach would have been taken. Perhaps there would be a single keyword for each fundamental type (that's the approach taken by C#, for example), or perhaps the fundamental type names would use some more coherent scheme rather than a jumble of keywords (say, int:2
for a 2-byte integer, unsigned:4
for a 4-byte unsigned integer). But both C and C++ are stuck with the current approach.
Reference: http://cm.bell-labs.com/cm/cs/who/dmr/cman.pdf
No, it can't be used with classes or structs since they're not integral types. All a template can do with it is make an int unsigned. I think it was chosen as a separate keyword since it can be applied to any integer type (char, int, long, long long), thereby achieving with one keyword what would have required four more. Its meaning is also immediately evident, whereas uint, uchar, etc. aren't necessarily. And keep in mind it can also be used by itself without a qualifier, in which case unsigned int is assumed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With