union initialisation

狂风中的少年 提交于 2019-12-04 04:11:46

You would want to do this:

a temp = {i: w};

That should work for both gcc and g++.

In C99 you can do this:

a temp = { .i=w };

In C99 you can do use named initialization as in:

a x = { .i = 10 };

There are some suggestion for using the non-standard gcc extension, but I would avoid it if coding C :

a x = { i : 10 };

You can use a function to initialize:

inline a initialize( int value ) { // probably choose a better name
   a tmp;
   tmp.i = value;
   return a;
}

and then use:

a x = initialize( 10 );

The compiler will optimize the copies away.

If you are doing C++, you can provide a constructor for your union type:

/*typedef*/ union u {           // typedef is not required in general in C++
    char bytes[sizeof(int)];
    int i;
    u( int i = 0 ) : i(i) {}
} /*u*/;

u x( 5 );

You can initialise the integer member like this:

a temp = {
  .i = w
};
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!