Union Misalignment?

B

Bryan Parkoff

byte and word and double word are always in alignment. Do C++ Compiler
fill the zero as padding inside byte's field and word's field to avoid
misalignment? It looks like that union does not use shift which it loads
data from memory. It is like "(H << 8) | L".
Intel Pentium 4 can degrade the performance if shift is used heavily,
but union may be recommended to avoid using shift. It may be slow to store
two bytes into memory before load one word from memory containing two bytes.
union example is below.
Please advise.

union var
{
struct
{
unsigned __int8 L;
unsigned __int8 H;
};
struct
{
unsigned __int16 W;
};
};

Bryan Parkoff
 
J

Jack Klein

byte and word and double word are always in alignment. Do C++ Compiler
fill the zero as padding inside byte's field and word's field to avoid
misalignment? It looks like that union does not use shift which it loads
data from memory. It is like "(H << 8) | L".

That is not something specified by the language. It depends on the
compiler, and quite possibly on options that you use when you run the
compiler.
Intel Pentium 4 can degrade the performance if shift is used heavily,
but union may be recommended to avoid using shift. It may be slow to store
two bytes into memory before load one word from memory containing two bytes.
union example is below.
Please advise.

The C++ language knows nothing at all about the Intel Pentium 4 or any
other particular processor. How well a particular compiler optimizes
the object code for any particular processor is a QOI (Quality Of
Optimization) issue. The language standard only specifies what the
observable output of a strictly conforming program must be. It does
not specify how fast the output must be produced or how small the
executable image must be.
union var
{
struct
{
unsigned __int8 L;
unsigned __int8 H;
};
struct
{
unsigned __int16 W;
};
};

Bryan Parkoff

I have heard anecdotally that Intel's compilers, for example, generate
more optimized code for Intel processors than Microsoft's compilers
do. I have no knowledge whether this is correct.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,825
Latest member
VernonQuy6

Latest Threads

Top