Re: Struct vs Union on TCP/IP code
- From: "Michael Jørgensen" <ccc59035@xxxxxxxxxxxxxxxx>
- Date: Wed, 26 Oct 2005 08:05:20 +0200
"grocery_stocker" <cdalten@xxxxxxxxx> wrote in message
news:1130287766.285401.269310@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
> When finding the byte order, why would someone write like the
> following:
Byte-order is not something you should determine at run-time. There are more
beasts around than big-endians and little-endians. You have middle-endians
too (trust me, I'm not joking). Some machines do not have 8-bit bytes
either. And so on. And when you suddenly compile this code on some new CPU
from MegaFlop Inc. it won't work as intended, because they have perhaps
written their processor using inside-out-endians (a new name to indicate
that this scheme is different than the rest).
In other words, endianness is something that should be determined at (or
before) compile time, like e.g. a MACRO.
>
> union {
> short s;
> char c[sizeof(short)];
> } un;
>
> un.s = 0x0102;
>
> Why use a union over a structure?
Well, the whole point of this construction is that the 's' and the 'c' are
expected to share the same memory location. On a little-endian, you'd then
expect un.c[0] == 0x01. If you used a structure, the compiler will *for
sure* place 's' and 'c' in different memory locations. Mind you, for a union
it may choose to do so as well.
-Michael.
.
- References:
- Struct vs Union on TCP/IP code
- From: grocery_stocker
- Struct vs Union on TCP/IP code
- Prev by Date: Re: Java or C++?
- Next by Date: Re: please check my homework
- Previous by thread: Re: Struct vs Union on TCP/IP code
- Next by thread: Re: Struct vs Union on TCP/IP code
- Index(es):
Relevant Pages
|