P
P
pixik2016-10-13 17:11:35
C++ / C#
pixik, 2016-10-13 17:11:35

What is the difference between #pragma pack(1) and #pragma pack(push, 1)?

Good afternoon!
I met the following line in the code:
#pragma pack(push, 1)
I tried to compile with and without push, the result is the same. Please tell me, if there is a difference, then what?
Here is an example:

#include <iostream>
using namespace std;


typedef struct{
  int a = 1;
  char b = 'x';
  long c = 0;
} A;

#pragma pack(push, 1)
typedef struct{
  int a = 1;
  char b = 'x';
  long c = 0;
} B;

#pragma pack(2)
typedef struct{
  int a = 1;
  char b = 'x';
  long c = 0;
} C;
#pragma pack(push, 2)
typedef struct{
  int a = 1;
  char b = 'x';
  long c = 0;
} D;

int main() {
  // your code goes here
  A a;
  B b;
  C c;
  D d;
  cout << "A = " << sizeof(a) << endl;
  cout << "B = " << sizeof(b) << endl;
  cout << "C = " << sizeof(c) << endl;
  cout << "D = " << sizeof(d) << endl;
  return 0;
}

and output:
A = 12
B = 9
C = 10
D = 10

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rsa97, 2016-10-13
@pixik

push pushes the current value to the top of the stack, which can then be restored with #pragma pack(pop).
This avoids conflicts when building multiple .h files with different pack requirements.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question