Size of Primitive data types

前端 未结 6 2203
旧时难觅i
旧时难觅i 2020-12-03 18:22

On what exactly does the size of a primitive data type like int depend on?

  • Compiler
  • Processor
  • Development Environment
6条回答
  •  长情又很酷
    2020-12-03 18:40

    As I commented under @Nawaz's answer, it technically depends solely on the compiler.

    The compiler is just tasked with taking valid C++ code, and outputting valid machine code (or whatever language it targets).

    So a C++ compiler could decide to make an int have a size of 15, and require it to be aligned on 5-byte boundaries, and it could decide to insert arbitrary padding between the variables in a POD. Nothing in the standard prohibits this, and it could still generate working code.

    It'd just be much slower.

    So in practice, compilers take some hints from the system they're running on, in two ways: - the CPU has certain preferences: for example, it may have 32-bit wide registers, so making an int 32 bits wide would be a good idea, and it usually requires variables to be naturally aligned (a 4-byte wide variable must be aligned on an address divisible by 4, for example), so a sensible compiler respects these preferences because it yields faster code. - the OS may have some influence too, in that if it uses another ABI than the compiler, making system calls is going to be needlessly difficult.

    But those are just practical considerations to make life a bit easier for the programmer or to generate faster code. They're not required.

    The compiler has the final word, and it can choose to completely ignore both the CPU and the OS. As long as it generates a working executable with the semantics specified in the C++ standard.

提交回复
热议问题