Purpose of Unions in C and C++

后端 未结 16 2111
予麋鹿
予麋鹿 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:32

    The most common use of union I regularly come across is aliasing.

    Consider the following:

    union Vector3f
    {
      struct{ float x,y,z ; } ;
      float elts[3];
    }
    

    What does this do? It allows clean, neat access of a Vector3f vec;'s members by either name:

    vec.x=vec.y=vec.z=1.f ;
    

    or by integer access into the array

    for( int i = 0 ; i < 3 ; i++ )
      vec.elts[i]=1.f;
    

    In some cases, accessing by name is the clearest thing you can do. In other cases, especially when the axis is chosen programmatically, the easier thing to do is to access the axis by numerical index - 0 for x, 1 for y, and 2 for z.

提交回复
热议问题