c++ - What is the reason for naming unions? -


why name union if compiler treats object anonymous, regardless whether or not union named?

my implementation looks this:

typedef struct _dmessageheader {     union _msgid {         unsigned char ucmsgid;         unsigned short usmsgid;         unsigned long ulmsgid;         unsigned long long ullmsgid;     } msgid; } dmsg_hdr, *pdmsg_hdr; 

i'd able access this, compiler throws error:

pdmsg_desc ptmsg->hdr.msgid = id_in; 

it allows me directly access union member this:

pdmsg_desc ptmsg->hdr.msgid.ucmsgid = id_in; 

any thoughts why is, or how may access union name?

i'm not sure why use union in case @ all. please note size of struct 8 bytes (size of long long) on 64bit machine.

#include <iostream> using std::cout; using std::endl; typedef struct _dmessageheader {     union _msgid {         unsigned char ucmsgid;         unsigned short usmsgid;         unsigned long ulmsgid;         unsigned long long ullmsgid;     }  msgid; } dmsg_hdr, *pdmsg_hdr;  int main( int argc , char ** argv, char ** env) {     cout<<"sizof dmessageheader"<<sizeof(dmsg_hdr)<<endl;     return 0; } 

if store in union msgid single id of varying length (1 - 8) bytes depending on architecture) , have no memory constrains rewrite struct following:

typedef struct _dmessageheader { unsigned long long msgid; } dmsg_hdr, *pdmsg_hdr; dmsg_hdr hdr; hdr.msgid = id_in; 

also suggest reading this thread thorough discussion using unions in c++.


Comments

Popular posts from this blog

authentication - Mongodb revoke acccess to connect test database -

r - Update two sets of radiobuttons reactively - shiny -

ios - Realm over CoreData should I use NSFetchedResultController or a Dictionary? -