Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any difference between structure and union if we have only one member?

I would like to know the difference between structure and union for one member data type if there is any.

like image 748
RAFI KC Avatar asked Oct 26 '14 11:10

RAFI KC


People also ask

How does a structure differ from a union?

A structure can store multiple values of the different members. A structure's total size is the sum of the size of every data member. A union's total size is the size of the largest data member. Users can access or retrieve any member at a time.

Can union be a structure member?

Neither a structure nor union member can have a function type or an incomplete type. Structures and unions cannot contain instances of themselves as members, but they can have pointers to instances of themselves as members. The declaration of a structure with no members is accepted; its size is zero.

Which is better structure or union?

If you want to use same memory location for two or more members, union is the best for that. Unions are similar to the structure. Union variables are created in same manner as structure variables. The keyword “union” is used to define unions in C language.

What is important difference between structure & union * 1 point there is no difference union takes less memory union is faster structure is faster?

The concept of structure and union are same. Both are created to collect different data type in one variable. The only difference is in memory management i.e. Memory requirement of the two.


1 Answers

In C: None. The famous "space-saving joke" #define struct union is almost not a joke.

In C++98: Unions can only have POD members, non-union classes can have arbitrary members.

In C++11: Unions can have arbitrary data members of object type (but not of reference type), but their use is more restricted that that of non-union classes. (Namely: a union cannot have virtual member functions, cannot be a base class and cannot have base classes.) Also, you have to write more code to make a one-member union work as opposed to a one-member non-union class, since you have to write constructors and the destructor yourself.

like image 175
Kerrek SB Avatar answered Sep 23 '22 17:09

Kerrek SB