简体   繁体   中英

sizeof(int) <= sizeof(long) <= sizeof(long long) always true?

From C standard, int has of at least 16bit, long has of at least 32bit and at least 64bit for long long if any (some platforms may not support). Just wondering if the sentence as title is always true.

No. The standard only defines the minimum ranges for each of those types. Conceivably int could have a 16-bit range, but 48 bits of padding, bringing it to 64-bits (8 bytes, if CHAR_BITS == 8), while long is 32-bits (4 bytes).

Of course, this would be silly. But it's not forbidden, as such.

Note, however, that sizeof(char) == 1 , by definition. So sizeof(char) <= sizeof( anything else ) .

According to C Programming/Reference Tables , particularly the Table of Data Types :

int ≥ 16 ≥ size of short

long ≥ 32 ≥ size of int

long long ≥ 64 ≥ size of long

As bdonlan pointed out, this only refers to the range of the values, not the size in memory (which sizeof returns in bytes). The C standard doesn't specify the size in memory that each type can use, so it's left to the implementation.

Practical C++ Programming says that

C++ guarantees that the storage for short <= int <= long

Still searching for long long .

At least for ISO C++, this is well-defined (excepting long long for obvious reasons) by the Standard in 3.9.1[basic.fundamental]/2:

There are four signed integer types: “signed char”, “short int”, “int”, and “long int.” In this list, each type provides at least as much storage as those preceding it in the list.

Note that this is speaking of storage, not value ranges. This specifically means sizeof .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM