1.

Differentiate between struct and union in the context of C programming language.

Answer»
  • STRUCT: In C, a structure is a user-defined data type that allows you to combine data objects of various types. A record is represented by a structure.

Syntax:

 struct structureName { member DEFINITION; member definition; ... member definition; };
  • union: In C, a union is a unique data type that allows you to store many data types in the same memory region. A union can have numerous members, but only ONE of them can have a value at any given time. Unions are a useful approach to reuse the same memory space for numerous purposes.

Syntax:

 union unionName { member definition; member definition; ... member definition; };

The following table illustrates the differences between struct and union:

struct union
A structure is defined using the struct keyword. Union is defined by the keyword union.
The compiler allocates memory to each VARIABLE member when the variables are declared in a structure. The total size of each data member determines the size of a structure.When a variable is declared in a union, the compiler allocates memory to the variable member with the largest size. A union's size is determined by the size of its largest data member.
Changing a variable's value has no effect on other variables present in the struct.Changing the value of one variable member will have an impact on the other variables present in the union.
Each variable's member has its own memory area.Members of a variable share the memory space of the variable with the largest size.
Multiple variables in a structure can be initialised at the same time.Only the first data member of a union can be initialised.
At any point in the program, all variable members store some value.At any given point in the program, exactly one data member stores a value.
It's used to keep track of various data types' values.It's used to save one value at a time from a variety of data types.
It provides for the simultaneous access and retrieval of any data member.It lets you access and retrieves individual data members at a time.


Discussion

No Comment Found