Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the unsigned keyword affect the result of sizeof?

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?

like image 252
typ1232 Avatar asked May 17 '13 19:05

typ1232


People also ask

Is sizeof signed or unsigned?

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.

What happens when an unsigned integer variable overflows?

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.

What happens when unsigned int goes negative?

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).


2 Answers

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.

like image 182
jrok Avatar answered Oct 21 '22 05:10

jrok


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

like image 21
Angew is no longer proud of SO Avatar answered Oct 21 '22 04:10

Angew is no longer proud of SO