Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Always same effect of #pragma pack(16) and #pragma pack(8)?

I am trying to align data members by using #pragma pack (n). Take the following as an example:

#include <iostream>
using namespace std;

#pragma pack(8) // or (16)

struct A
{
    int a;
    char b;
    char c;
    char d;
    char e;
    char f;
    double g;
};
int main()
{
    cout << sizeof(A) << endl;

    return 0;
}

Both will print 24 for #pragma pack(8) and #pragma pack(16). I can understand the result for n=8 with the data alignment, of my understanding, as follows:

Bytes: |1 2 3 4|5|6|7|8|9|10 11 12 13 14 15 16|17 18 19 20 21 22 23 24|
 Data: |a      |b|c|d|e|f|padding             |g                      |

But I cannot understand why the result is still 24 for n=16. I also tried other examples, all of them seems to give same result for n=8 and n=16. Can someone explain why? Are the data members aligned the same way as n=8?

P.S.: Tested in VS2010 under Win-x64.

like image 543
herohuyongtao Avatar asked Dec 04 '25 10:12

herohuyongtao


1 Answers

From the page you linked to:

The alignment of a member will be on a boundary that is either a multiple of n or a multiple of the size of the member, whichever is smaller.

For each member it takes the minimum alignment, between the member's optimal alignment and the pack value. The members in your example are aligned exactly the same regardless of pack(8) and pack(16) because the optimal alignment of the types are all less than 16.

If you had a member that required 16-byte alignment, such as __m128, you would be able to find different results.

like image 111
Cory Nelson Avatar answered Dec 05 '25 23:12

Cory Nelson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!