Union of same type in C++

人走茶凉 提交于 2019-12-19 18:54:28

问题


Whenever I see examples of union, they are always different types. For example, from MSDN:

// declaring_a_union.cpp
union DATATYPE    // Declare union type
{
    char   ch;
    int    i;
    long   l;
    float  f;
    double d;
} var1;          // Optional declaration of union variable

int main()
{
}

What happens if I have a union (in this case anonymous, but that shouldn't matter) like this:

union
{
    float m_1stVar;
    float m_1stVarAlternateName;
};

Regardless of whether this is good practice or not, will this cause any issues?


回答1:


No, this won't cause any issues. The reason you don't see it more often is that it's pointless - both names refer to the same value of the same type.




回答2:


An issue would arise only if you want to have unique values for the two variables. In your use-case, it should work fine.



来源:https://stackoverflow.com/questions/6512710/union-of-same-type-in-c

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