Hi all~
if union could supply only int and float data ?
I tried some other types but no correct response for me. :(
Printable View
Hi all~
if union could supply only int and float data ?
I tried some other types but no correct response for me. :(
union can supply more than int and float:
Code:#include <limits.h>
#include <iostream.h>
union UNION
{
short s;
unsigned int i;
char ch;
long l;
union
{
char c;
unsigned char uc;
};
};
int main()
{
UNION u;
u.ch = 'a';
cout << "ch = " << u.ch << endl;
u.s = SHRT_MAX;
cout << "MAX SHORT = " << u.s << endl;
u.i = UINT_MAX;
cout << "MAX UNIT = " << u.i << endl;
u.l = LONG_MAX;
cout << "MAX LONG = " << u.l << endl;
u.uc = UCHAR_MAX;
cout << "MAX CHAR = " << (int)u.uc << endl;
return 0;
}
>if union could supply only int and float data ?
A union can supply any data type, but only one at a time.
-Prelude
Just curious, Prelude. Why do you always end your posts/replies with -Prelude?
I mean, no one can be so lazy they can't turn their head 5 degrees to the left and see it there? :D
(Just curious, that's all. No offense intended)
any data type ? I tried string but got an error. :rolleyes:Quote:
Originally posted by Prelude
>if union could supply only int and float data ?
A union can supply any data type, but only one at a time.
-Prelude
a struct or typedef struct might suit your needs better if your using strings
Mmm...........then what is the advantage of union please ? :rolleyes:Quote:
Originally posted by Vicious
a struct or typedef struct might suit your needs better if your using strings
lol, dunno...
i might not even be right about that :rolleyes:
>any data type ? I tried string but got an error.
I'm sorry, I thought I had said "almost any type". Some class objects will cause problems with the memory handling of unions, such as the string class. Built in types are guaranteed, but user defined data types can be invalid because of overloaded operators, constructor features, etc...
>Why do you always end your posts/replies with -Prelude?
Two reasons: First, I got into the habit and never got out of it. Second, in case I get logged out while responding with a lengthy post, the readers will still know who I was. It's all about ego. :D
>then what is the advantage of union please ?
They are a way of avoiding bloated code when space is at a premium. Most of the time you won't use them, but it's nice to have the option of optimizing for space when you need it.
-Prelude