Howdy, Stranger!

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

Categories

Usage of #pragma pack(1)

ligangligang Member Posts: 76
#pragma pack(1)

Is it for saving memory purpose ?

Comments

  • DariusDarius Member Posts: 1,666
    : #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

  • Chris BrownChris Brown USAMember Posts: 4,496 ✭✭

    ____ { http://forcoder.org } free video tutorials and ebooks about < Visual Basic Perl JavaScript PHP C++ Ruby PL/SQL Swift MATLAB Python Scratch C Visual Basic .NET C# Java Assembly Go Objective-C Delphi R ABAP Clojure Fortran LabVIEW Scala Alice Logo ML Prolog Transact-SQL Erlang Kotlin Lua Julia Hack Dart Lisp Crystal Awk COBOL FoxPro D Bash SAS Apex Rust Ada VBScript F# Scheme /> _____

Sign In or Register to comment.