Archived

This topic is now archived and is closed to further replies.

kungfulkoder

Unions

Recommended Posts

Null and Void    1088
quote:
Original post by kungfulkoder
Does anyone know cases where a union would be "better" to implement over a class or struct defenition?

Where you only want (need) one of the members to be valid at a time is the most common situation that comes to mind.

Share this post


Link to post
Share on other sites
jwalker    122

  

typedef struct INT64
{
union
{
int32 high;
int32 low;
};

int64 var;
}INT64;

;

the union can be used to segment the variables if not supported....

{ Stating the obvious never helped any situation !! }

Share this post


Link to post
Share on other sites
Promit    13246
quote:
Original post by jwalker


    

typedef struct INT64
{
union
{
int32 high;
int32 low;
};

int64 var;
}INT64;

;

the union can be used to segment the variables if not supported....

{ Stating the obvious never helped any situation !! }

How does that work? That''s not the correct structure for a LARGE_INTEGER type, and it''s not INT64 either. the union won''t segment the vars, it''ll push them together into the most profoundly useless structure ever.

INT64 is
typedef __int64 INT64

____________________________________________________________
Direct3D vs. OpenGL

Share this post


Link to post
Share on other sites
Neophyte    595
Promit: You probably mean

  
typedef struct INT64 {
union {
int64 var;
struct {
int32 high;
int32 low;
};
};
};


-Neophyte

-----BEGIN GEEK CODE BLOCK-----
Version: 3.1
GED d- s:+ a- C++$ UL++ P++ L++ E W+ N+ o K? w !O M--(+) V-- PS+
PE Y+ PGP t-- 5++ X+ R(+) rv+(++) b+++ DI+ D(+) G e+>++ h r--> y+
----- END GEEK CODE BLOCK-----
geekcode.com

Share this post


Link to post
Share on other sites
Promit    13246
Yeah, that looks right. And at least In MSVC, I''m pretty sure that typedef is for LARGE_INTEGER and not for INT64. You can cast between INT64 which is __int64 and LARGE_INTEGER which is that union with the segmented var struct in it.

____________________________________________________________
Direct3D vs. OpenGL

Share this post


Link to post
Share on other sites
Ksero    262
Another use I''ve been thinking about is:

  
union vector
{
float v[3];
struct w
{
float x;
float y;
float z;
};
};

Giving a vector datatype that can be accessed by X,Y,Z or as an array...
(note: I''ve never used union, I hope the syntax is correct)
/Ksero

Share this post


Link to post
Share on other sites
Promit    13246
That comes in very useful, esp. when you want to support both typical OpenGL style structures and D3D style structures.

Then again, you might actually be able to cast between typedef struct vec3_s { float x, y, z; } vec3_t; and vec3[3]; . Not sure...

____________________________________________________________
Direct3D vs. OpenGL

Share this post


Link to post
Share on other sites