Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ union array and vars?

Tags:

c++

unions

There's no way to do something like this, in C++ is there?

union {
    {
        Scalar x, y;
    }
    Scalar v[2];
};

Where x == v[0] and y == v[1]?

like image 390
mpen Avatar asked Mar 31 '09 19:03

mpen


People also ask

How does structure differ from an array and union?

Array has no padding in between its elements as compared to structure. All elements of array and structure are considered for total size calculation, while union size is equal to its maximum sized element. Array have all elements of same type, which is no prerequisite for structure and union.

Can we use array in union?

When array of unions are created it will create each element of the array as individual unions with all the features of union. That means, each array element will be allocated a memory which is equivalent to the maximum size of the union member and any one of the union member will be accessed by array element.

What is the advantage of structure differentiate it with union and arrays?

Structure is mainly used for storing various data types while union is mainly used for storing one of the many data types. In structure, you can retrieve any member at a time on the other hand in union, you can access one member at a time. Structure supports flexible array while union does not support a flexible array.


1 Answers

How about

union {
    struct {
        int x;
        int y;
    };
    int v[2];
};

edit:

union a {
    struct b { int first, second; } bee;
    int v[2];
};

Ugly, but that's more accurate

like image 80
fido Avatar answered Oct 05 '22 02:10

fido