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

偶尔善良 提交于 2019-12-06 16:44:51

问题


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 ?


回答1:


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 [...]




回答2:


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.



来源:https://stackoverflow.com/questions/13169451/do-i-have-the-guarantee-that-sizeoftype-sizeofunsigned-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!