Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I have the guarantee that sizeof(type) == sizeof(unsigned type)?

The sizeof char, int, long double... can vary from one compiler to another. But do I have the guarantee according to the C++11 or C11 standard that the size of any signed and unsigned fundamental integral type is the same ?

like image 563
Vincent Avatar asked Nov 01 '12 00:11

Vincent


People also ask

Is sizeof signed or unsigned?

The result of sizeof is of unsigned integral type which is usually denoted by size_t.

Is size of char fixed?

The CHAR data type is of fixed-length. For example, a CHAR(25) column requires 25 bytes of storage for all values, so the string “This is a text string” uses 25 bytes of storage. A varying-length column size can be the number of bytes occupied by its data.

What is the size of signed and unsigned integer?

A signed integer is a 32-bit datum that encodes an integer in the range [-2147483648 to 2147483647]. An unsigned integer is a 32-bit datum that encodes a nonnegative integer in the range [0 to 4294967295]. The signed integer is represented in twos complement notation.


1 Answers

The C++11 Standard says about integer types:

(§3.9.1/3) For each of the standard signed integer types, there exists a corresponding (but different) standard unsigned 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 type; that is, each signed integer type has the same object representation as its corresponding unsigned integer type. Likewise, for each of the extended signed integer types there exists a corresponding extended unsigned integer type with the same amount of storage and alignment requirements. [...]

So the answer is yes.

For C11, there is a corresponding statement here (this is from 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 [...]

like image 85
jogojapan Avatar answered Oct 21 '22 18:10

jogojapan