Purpose of Unions in C and C++

后端 未结 16 2192
予麋鹿
予麋鹿 2020-11-22 06:55

I have used unions earlier comfortably; today I was alarmed when I read this post and came to know that this code

union ARGB
{
    uint32_t colour;

    str         


        
16条回答
  •  甜味超标
    2020-11-22 07:41

    You can use a a union for two main reasons:

    1. A handy way to access the same data in different ways, like in your example
    2. A way to save space when there are different data members of which only one can ever be 'active'

    1 Is really more of a C-style hack to short-cut writing code on the basis you know how the target system's memory architecture works. As already said you can normally get away with it if you don't actually target lots of different platforms. I believe some compilers might let you use packing directives also (I know they do on structs)?

    A good example of 2. can be found in the VARIANT type used extensively in COM.

提交回复
热议问题