Why does sizeof(int) vary across different operating systems?

后端 未结 4 1716
-上瘾入骨i
-上瘾入骨i 2020-12-02 00:55

I wounder why size of int depends on which OS one is using ,in C & C++. It\'s ok if size of pointer varies, but why size of integer. If 16 bit OS sizeof(int) = 2 byte, f

4条回答
  •  自闭症患者
    2020-12-02 01:28

    According to the C++ standard

    1.7.1 states:

    The fundamental storage unit in the C++ memory model is the byte. A byte is at least large enough to contain any member of the basic execution character set ...

    then 3.9.1.1 states:

    Objects declared as characters (char) shall be large enough to store any member of the implementation’s basic character set.

    So we can infer that char is actually a byte. Most importantly 3.9.1.2 also says:

    There are five signed integer types: “signed char”, “short int”, “int”, “long int”, and “long 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 environment; the other signed integer types are provided to meet special needs.

    So in other words the size of int is (a) guaranteed to be at least a byte and (b) naturally aligned to the OS/hardware it's running on so most likely these days to be 64 bit or (for many older systems) 32 bit.

提交回复
热议问题