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.
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.
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.
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.
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.
You can still initialize the union as follows:
const union un a = { .i = 100 };
then use it in your code.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With