Why is the “alignment” the same on 32-bit and 64-bit systems?

后端 未结 4 1443
暗喜
暗喜 2021-02-19 00:16

I was wondering whether the compiler would use different padding on 32-bit and 64-bit systems, so I wrote the code below in a simple VS2019 C++ console project:

         


        
4条回答
  •  终归单人心
    2021-02-19 01:01

    This is a matter of alignment requirement of the data type as specified in Padding and Alignment of Structure Members

    Every data object has an alignment-requirement. The alignment-requirement for all data except structures, unions, and arrays is either the size of the object or the current packing size (specified with either /Zp or the pack pragma, whichever is less).

    And the default value for structure member alignment is specified in /Zp (Struct Member Alignment)

    The available packing values are described in the following table:

    /Zp argument Effect
    1 Packs structures on 1-byte boundaries. Same as /Zp.
    2 Packs structures on 2-byte boundaries.
    4 Packs structures on 4-byte boundaries.
    8 Packs structures on 8-byte boundaries (default for x86, ARM, and ARM64).
    16 Packs structures on 16-byte boundaries (default for x64).

    Since the default for x86 is /Zp8 which is 8 bytes, the output is 16.

    However, you can specify a different packing size with /Zp option.
    Here is a Live Demo with /Zp4 which gives the output as 12 instead of 16.

提交回复
热议问题