Union in C

The syntax of Union in C programming language is identical to structure except for the keyword.

Syntax of Union in C Programming Language



Union Tag-name

<Datatype1> m1

<Datatype2> m2

.

.

.

}union-var;

Simple example explaining union in c programming language

Union Student

{

Int rollnumber;

Char name[15];

};

main()

Union student stud;

Printf(“enter student roll number”);

Scanf(“%d”,&stud.rollnumber);

Printf(“enter student name”);

Scanf(%s,&stud.name);

Printf(“detail of student”);

Printf(“rollnumber:%d”stud.rollnumber);

Printf(“student name:%s”stud.name);

getch();

}

Difference between Union and Structure

In Union, Same memory location is shared by all the members and change of the modification of one variable affect another variable.

The Union can handle one member at a time.

In Structure, Every member is allocated with the different memory location and they are independent of each other.

Leave a Reply

avatar
  Subscribe  
Notify of