Difference between Structure and Union in C

C++ProgrammingServer Side Programming

Structure

Structure is a user defined datatype. It is used to combine different types of data into a single type. It can have multiple members and structure variables. The keyword “struct” is used to define structures in C language. Structure members can be accessed by using dot(.) operator.

Here is the syntax of structures in C language,

struct structure_name {
   member definition;
} structure_variables;

Here,

  • structure_name − Any name given to the structure.

  • member definition − Set of member variables.

  • structure_variable − This is the object of structure.

Here is an example of structures in C language,

Example

 Live Demo

#include <stdio.h>
#include <string.h>

struct Data {
   int i;
   long int f;
} data, data1;

int main( ) {
   data.i = 28;
   printf("The value of i : %d\n", (data.i));
   printf( "Memory size occupied by data : %d\t%d", sizeof(data), sizeof(data1));
   return 0;
}

Output

Here is the output

The value of i : 28
Memory size occupied by data : 16 16

Union

Union is also a user defined datatype. All the members of union share the 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.

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.

Here is the syntax of unions in C language,

union union_name {
   member definition;
} union_variables;

Here,

  • union_name − Any name given to the union.

  • member definition − Set of member variables.

  • union_variable − This is the object of union.

Here is an example of unions in C language,

Example

 Live Demo

#include <stdio.h>
#include <string.h>

union Data {
   int i;
   float f;
} data, data1;

int main( ) {
   printf( "Memory size occupied by data : %d\t%d", sizeof(data), sizeof(data1));
   return 0;
}

Output

Here is the output

Memory size occupied by data : 4 4
raja
Published on 24-Oct-2018 13:56:09
Advertisements