Naming Array Elements, or Struct And Array Within a Union

前端 未结 4 1833
梦毁少年i
梦毁少年i 2021-01-17 13:50

Consider the following struct:

struct Vector4D
{
   union
   {
      double components[4];
      struct { double x, y, z, t; } Endpoint;
   };
};
         


        
4条回答
  •  温柔的废话
    2021-01-17 14:06

    When it comes to the standard, there are two problems with it:

    • It is unspecified what happens when writing to an element in a union and reading from another, see the C standard 6.2.6.1 and K.1
    • The standard does not guarantee the layout of the struct match that of the layout of the array, see the C standard 6.7.2.1.10 for details.

    Having said this, in practice this will work on normal compilers. In fact, this kind of code is widely spread and is often used to reinterpret values of one type into values of another type.

提交回复
热议问题