Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
146 views
in Technique[技术] by (71.8m points)

c++ - 3-byte int and 5-byte long?

Does each of C and C++ standards allow sizeof of numeric types not to be a power of two?

The following constraints are known:

  • 16 <= CHAR_BIT * sizeof(int) <= CHAR_BIT * sizeof(long)
  • 32 <= CHAR_BIT * sizeof(long) <= CHAR_BIT * sizeof(long long)
  • and a dozen of others, which on a typical 8-bit byte architecture means 2 <= sizeof(int) && 4 <= sizeof(long)

Does that mean that sizeof(int) == 3 && sizeof(long) == 5 is a valid behaviour?

If yes - is there any known compiler/architecture behaving in a similar way?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think 3.9.1/2 (C++98) sums this up nicely (immediately followed by analogous information for the unsigned types):

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. Plain ints have the natural size suggested by the architecture of the execution environment39) ; the other signed integer types are provided to meet special needs.

Basically all we know is that sizeof(char) == 1 and that each "larger" type is at least that large, with int being a "natural" size for an architecture (where as far as I can tell "natural" is up to the compiler writer). We don't know anything like CHAR_BIT * sizeof(int) <= 32 etc. Also keep in mind that CHAR_BIT doesn't have to be 8 either.

It seems fairly safe to say that three byte int and five byte long would be allowed for hardware where those sizes were natively used. I am however not aware of any such hardware/architectures.

EDIT: As pointed out in @Nigel Harper comment we do know that int has to be at least 16 bits and long at least 32 bits to satisfy range requirements. Otherwise we don't have any specific size restrictions other than as seen above.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...