Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

It's not really obsolete, more like redundant. The standard does guarantee signed and unsigned variations of a type to have the same size.

You could always put in some code like this

{
char s1[1 + sizeof(int) - sizeof(unsigned int)];
char s2[1 + sizeof(unsigned int) - sizeof(int)];
}

(probably only in debug builds)

This will give you a compile time failure if they were ever different sizes.

I do this occasionally for highly (typedef)ed code I'm refactoring.

But unsigned and signed varieties are always the same size.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top