We discussed about the union keyword on the previous threads 2-3 days
earlier. I want to add. Two byte data inside struct and one word data are
inside union. You modify word data. Then two byte data are modified
automatically because two byte data and one word data are sharing the same
memory address. Let's move on and forget union because we claim that union
keyword is not the language of C/C++ Compiler.
Here is a pointer variable code below.
enum
{
Low = 0,
High = 1
};
U_BYTE B[4] = { 0xFF, 0x20, 0x02, 0x22 };
PU_WORD W = (PU_WORD)&B;
PU_DWORD DW = (PU_DWORD)&B;
B[Low] += 0x0A;
B[High] += 0x01;
W[Low] += 0x0100;
*DW = 0x41424344; // *DW and DW[0] are same.
DW[0] = 0x51525354;
I decide to define four elements in an array of B variable. I define W
as the pointer to B variable. This allows to modify individual two byte
data. Then W variable is modified automatically from B variable. W
variable is modified causing two byte data to be modified automatically. DW
variable does the same to modify 4 byte data. Sometimes, I want to modify
individual byte data and word data, but I depend on word data often. I load
two byte data from big array in memory and they are stored in B[L] and B[H].
I use addition to put two byte data together into word data so I don't need
to use addition on both byte data. It depends according to my decision and
design of my source code.
You may be surprised to see direct variable and pointer variable. You
set debug mode. You go step by step looking at each variable in watch
window. You go into disassemble window like x86 machine and non-x86
machine. You can see MOV instruction on direct variable. Also, you can see
LEA instruction and MOV instruction on pointer variable.
You switch from debug mode to release mode. You look at disassemble
window again. Do you see disappearing LEA instruction? W variable is
converted to direct variable from pointer variable. Do you know why? The
C/C++ Compiler uses optimization and it decides that two variables share the
same memory address so it does not need LEA instruction. It reduces time
and improve performance.
I choose word data instead of dword data, but you claim that word data
is slow than dword data. What happen if word data has 0xFFFF? It is added
by 0x0004. The result shows 0x0001-0003. I do not want data on 31th
through 16th bits. 32th through 16th bits can always be ignored. Word data
can be used. It is pain to use "AND" on dword data if you want to mask 16
bit data or 8 bit data.
Sometimes, C/C++ Compiler ignores "AND" like dword dw &= 0xFFFF and it
uses MOV instruction to store 16 bit data or 8 bit data into memory address
directly.
Please let me know what you think. It can be interesting discussion. I
may do not need to post more so I can continue writing my C++ source code
according to my design so two variables can share the same memory address.
--
Yours Truly,
Bryan Parkoff