Do C and C++ guarantee that the unsigned equivalent of a type has the same size?
Example:
size_t size = sizeof(unsigned int);
Is the unsigned
completely moot here?
Yes, there is a full guarantee that sizeof(signed type) is equal to sizeof(unsigned type) since unsigned is only taking the space of negative numbers of signed type to increase its range.
In general, when an unsigned int overflows, it rolls over to zero. So UINT_MAX + 5 rolls over and becomes 4. It would be the difference between the max uint value and the value of what would have been the overflow value.
An int is signed by default, meaning it can represent both positive and negative values. An unsigned is an integer that can never be negative. If you take an unsigned 0 and subtract 1 from it, the result wraps around, leaving a very large number (2^32-1 with the typical 32-bit integer size).
Both languages guarantee that signed and unsigned variants of a corresponding standard integer type have the same size.
C++, committee draft n3337, 3.9.1/3:
3 For each of the standard signed integer types, there exists a corresponding (but different) standard un- signed integer type: “unsigned char”, “unsigned short int”, “unsigned int”, “unsigned long int”, and “unsigned long long int”, each of which occupies the same amount of storage and has the same alignment requirements (3.11) as the corresponding signed integer type45; that is, each signed integer type has the same object representation as its corresponding unsigned integer type. [...]
For C, the wording is very similar
Taken from draft n1570, 6.2.5/6:
For each of the signed integer types, there is a corresponding (but different) unsigned integer type (designated with the keyword unsigned) that uses the same amount of storage (including sign information) and has the same alignment requirements. The type _Bool and the unsigned integer types that correspond to the standard signed integer types are the standard unsigned integer types. The unsigned integer types that correspond to the extended signed integer types are the extended unsigned integer types. The standard and extended unsigned integer types are collectively called unsigned integer types.
It's not really obsolete, more like redundant. The standard does guarantee signed and unsigned variations of a type to have the same size.
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