Re: Newbie question on unions
From: Rolf Magnus (ramagnus_at_t-online.de)
Date: 10/11/04
- Next message: Armin Menzel: "How to use vector with classes in it as return type?"
- Previous message: Rolf Magnus: "Re: Converting enums to pointers"
- In reply to: patleonard: "Newbie question on unions"
- Next in thread: Ron Natalie: "Re: Newbie question on unions"
- Reply: Ron Natalie: "Re: Newbie question on unions"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
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.
- Next message: Armin Menzel: "How to use vector with classes in it as return type?"
- Previous message: Rolf Magnus: "Re: Converting enums to pointers"
- In reply to: patleonard: "Newbie question on unions"
- Next in thread: Ron Natalie: "Re: Newbie question on unions"
- Reply: Ron Natalie: "Re: Newbie question on unions"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|
|