Re: Newbie question on unions

From: Rolf Magnus (ramagnus_at_t-online.de)
Date: 10/11/04


Date: Mon, 11 Oct 2004 12:07:18 +0200

patleonard wrote:

> The following code produces this output:
>
> Characters: XY
> Integer: 22872
>
> Where does the integer 22872 come from?
>
> #include <iostream.h>
>
> int main()
> {
> union test_union{
> short int i;
> char ch[2];
> } unvar;
>
> unvar.ch[0] = 'X';
> unvar.ch[1] = 'Y';
>
> cout << "Characters: " << unvar.ch[0] << unvar.ch[1] << '\n';
> cout << "Integer: " << unvar.i << '\n';

Reading a member of a union after writing to another one is not allowed in
C++. Most platforms I know will just give you a reinterpretation of the two
char values as one short value, but the right tool to do this is a
reinterpret_cast.

>
> return 0;
> }
>
> It may be a stupid question, but I don't know the answer. Any response
> will be helpful, thank you.



Relevant Pages

  • (long) An AES implementation for 32-bit platforms
    ... union BLOCK ... needed in the AES algorithm. ... typedef unsigned int word; ... void computetables() ...
    (sci.crypt)
  • Re: Unions Redux
    ... union {int s; unsigned int us;} u; ... depends on the object representation compatibility, ... all to do with the fact that there is a union involved. ... is a trap representation for signed int. ...
    (comp.lang.c)
  • Re: Nesting dis-similar hierarchies
    ... create table Teams(TeamIndex int, ReqTeamName varchar(5), TeamNumber int) ... UNION ... TeamIndex, ReqTeamName, TeamNumber, ...
    (microsoft.public.sqlserver.xml)
  • Re: void * pointer convert problem.
    ... >> int year; ... unions: if a union contains several structures that share a common ... _common initial sequence_ if corresponding members have compatible ...
    (comp.lang.c)
  • Re: Is this legal ?
    ... I wanted to have a union which has two structures in it. ... b.c:10: warning: ANSI C forbids member declarations with no members ...
    (comp.lang.c)