Usage of #pragma pack(1)

#pragma pack(1)

Is it for saving memory purpose ?


  • : #pragma pack(1)
    : Is it for saving memory purpose ?
    Potentially. It will have that effect, but it also may be necessary for other reasons.

    Basically, the pack pragma sets the alignment for the output file. For speed purposes, it's typically better to have data on machine word boundaries (4 bytes for 32-bit processors). Thus something like...

    struct two_chars{
    char a,b;

    would best be represented as 8 bytes, the six extra just being padding. Obviously this is inefficient space-wise (though the compiler will probably use appropriate setups to avoid being too inefficient).

    However, other reasons may make it necessary. For example, once code is compiled it expects the fields of structures to be at certain spots, and won't work correctly if they aren't. Low-level hardware-interfacing code often has very explicit offsets for data fields. In those cases the alignment MUST be the same as what was used when the other code was compiled.

    "We can't do nothing and think someone else will make it right."
    -Kyoto Now, Bad Religion

Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!


In this Discussion