Differences between structure and union in C are presented in the following table. Structure and union are different in some ways yet they are conceptually same and have following similarities too:
Both are container data types and can contain objects of any type, including other structures and unions or arrays as their members.
Both structures and unions support only assignment =
and sizeof
operators.
In particular, structures and unions cannot appear as operands of the equality ==
, inequality !=
, or typecast operators. The two structures or unions in the assignment must have the same members and member types.
Both structure and union can be passed by value to functions and returned by value by functions. The argument must have the same type as the function parameter. A structure or union is passed by value just like a scalar variable; that is, the entire structure or union is copied into the corresponding parameter
Structure:
1.Compiler allocates the memory for each member variable.
2.Modifying the value of any member variable value will not affect other member variables in the structure.
3.Multiple members of structure can be initialized at once.
4.Structure Example:
struct job 1 {
char name[32];
float salary;
int worker_no;
}s;
Here the memory allocated for structure job 1 is 7.
Union:
1.Compiler allocates memory based on size of largest member variable.
2.Modifying any member variable value in union will affect on other member variable values of it.
3.Only first member of a union can be intialized.
4. Union Example:
union car{ char name[50]; int price; }; Here the memory allocated for union car is 2.