Re: Use of unions



qqqmac@xxxxxxxxxxx wrote:
x = l;

should be x = r.l;

Is the code fragment above an example of correct use of a union?

It's not portable, and not a good example of anything.
If you want to transmit an integer value to another host
that might not have the same data format, then more care
is needed (e.g. XDR).

I have read books (1,2) that say the assignment to x is incorrect as the
component last used before this assignment is the character array, not
the long component.

If you use unsigned char (as DRT suggested in a previous response)
and the size of long is no more than 8 bytes, then if the input
bytes originally came from a valid long representation on the same
platform the reconstructed long value will be the same as the
original. The C standard specifically allows any data type to be
treated as an intermediate byte array of type unsigned char. That
is not to say that you often need to do that.
.



Relevant Pages

  • Re: Help me understand this compiler warning.
    ... ANDing an unsigned char with an ... int /could/ produce a signed int - which, according to 6.5.7, could ... 6.3.1.8- rules for integer promotions - adds a bit of ... which is of type unsigned char. ...
    (comp.lang.c)
  • Re: Help me understand this compiler warning.
    ... | The left operand is uc, which is of type unsigned char. ... | type unsigned char from being promoted to type int. ...
    (comp.lang.c)
  • Re: How to assign long to character array and later extract it
    ... How to assign long to character array and later extract it ... unsigned char carray; ... lval, sizeof lval); ...
    (comp.lang.c)
  • Re: [Lit.] Buffer overruns
    ... > value of which shall be representable as an unsigned char or shall ... > equal the value of the macro EOF. ... I had been going by Harbison and Steele's ... char be signed and also support a type unsigned char, ...
    (sci.crypt)
  • Re: Fast Image access for binarization
    ... Assuming that image has type unsigned char*, ... unsigned char *curpixel, *stop; ... bin_tbl initialization loop is fast. ...
    (sci.image.processing)