Re: Struct vs Union on TCP/IP code




"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.


.



Relevant Pages

  • Re: C examples and codes
    ... I don't know what you're talking about, but it's not standard ... Pointers are pointers. ... "1.13.10 union. ... You can store several values in a single memory location or a group ...
    (comp.lang.c)
  • Re: C examples and codes
    ... "1.13.10 union. ... You can store several values in a single memory location or a group ... jacob at jacob point remcomp point fr ...
    (comp.lang.c)
  • Re: Unions and Structure Questions
    ... > union can only use one item where a structure can use all? ... > string fname ... Whereas the members of a struct each occupy a different memory location, ...
    (alt.comp.lang.learn.c-cpp)
  • Re: strong/weak typing and pointers
    ... > Unions in functional languages are also known as direct sums of types (as ... > holds an int as list will yield an error - runtime, ... In OCaml, the error will be at compile time, and the compiler will warn you ... if you do not deal with all possible cases for a given union type. ...
    (comp.lang.python)