Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of a constant union object?

If I make a const union object (e.g in code below ), then no member assignment can be done in that. So is there any use of making a const union object, in any case ?

union un
{
    int i;
    float f;
    char c;
};
const union un a; 
/// ! a.i = 10; error.
like image 692
cirronimbo Avatar asked Aug 10 '12 08:08

cirronimbo


People also ask

What are unions used for in C++?

Union is a user-defined datatype. All the members of union share same memory location. Size of union is decided by the size of largest member of union. If you want to use same memory location for two or more members, union is the best for that.

Can unions have functions?

A union can have member functions (including constructors and destructors), but not virtual functions. A union cannot have base classes and cannot be used as a base class.

What is union in compiler?

A union is a special data type available in C that allows to store different data types in the same memory location. You can define a union with many members, but only one member can contain a value at any given time. Unions provide an efficient way of using the same memory location for multiple-purpose.

Can we use a structure inside a union?

A structure can be nested inside a union and it is called union of structures. It is possible to create a union inside a structure.


2 Answers

You can still initialize the union as follows:

const union un a = { .i = 100 }; 

then use it in your code.

like image 112
user1202136 Avatar answered Oct 20 '22 11:10

user1202136


You can still assign it at declaration, for instance like this:

const union un a = {0};

Update: that notation sets the first of the union members.

like image 43
Prof. Falken Avatar answered Oct 20 '22 11:10

Prof. Falken