Knowledge Walls
Venkatesan
Hyderabad, Andhra Pradesh, India
Passcode:
Introduction [cont'd]
Input Output Functions [cont'd]
Structures and Unions [cont'd]
# Preprocessor [cont'd]
Define Union in Structures and Unions of Programming in C
2244 Views
Define Union 
Union is also same as structure. But union is a shared memory, It is possible to assign and retrieve only one member value at a time. Next member value will collapse previous member data. Memory size shall be maximum size of a member.

Example
Union student{
int rno;
char student_name[20];
};

For above union example allocates 20 bytes.
Syntax 
union union_name
{
variables declaration;
};
Program
	#include
	//Allocates maximum memory needed by union members - 20 bytes
	//Set and Get the values from union immediatly
	union product {
	   int product_no;
	   char product_name[20];
	   float amount;
	};
	void main(){
	   union product pro;
	   pro.product_no = 123;
	   printf("%d\n",pro.product_no);
	   //When setting value for next member this collapse all other values of other members
	   //Union is a shared memory
	   strcpy(pro.product_name,"Dove");
	   printf("%d : %s",pro.product_no,pro.product_name);
	   pro.amount = 29.00f;
	   printf("%d : %s : %5.2f",pro.product_no,pro.product_name,pro.amount);
	}
Output 
123
28484 : Dove
0 : : 29.00
Next Topics
Next lessons of current book.
Previous Topics
Previous lessons of current book.
Structures and Unions of Programming in C
Structures and Unions of Programming in C
Structures and Unions of Programming in C
Structures and Unions of Programming in C
Structures and Unions of Programming in C
Best Lessons of "Programming in C"
Top lessons which are viewed more times.
Structures and Unions of Programming in C
Input Output Functions of Programming in C
Structures and Unions of Programming in C
  Copyright © 2014 Knowledge walls, All rights reserved
KnowledgeWalls
keep your tutorials and learnings with KnowledgeWalls. Don't lose your learnings hereafter. Save and revise it whenever required.
Click here for more details