Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

The GNU C Programming Tutorial - Declaration of unions

Node:Declaration of unions, Next:, Previous:union, Up:union



Declaration of unions

A union is declared in the same way as a structure. It has a list of members, as in the example below:

union int_or_float
{
  int int_member;
  float float_member;
};

Declaring union variables is similar to declaring structure variables:

union int_or_float my_union1, my_union2;

Just like structures, the members of unions can be accessed with the . and -> operators. However, unlike structures, the variables my_union1 and my_union2 above can be treated as either integers or floating-point variables at different times during the program. For example, if you write my_union1.int_member = 5;, then the program sees my_union1 as being an integer. (This is only a manner of speaking. However, my_union1 by itself does not have a value; only its members have values.) On the other hand, if you then type my_union1.float_member = 7.7;, the my_union variable loses its integer value. It is crucial to remember that a union variable can only have one type at the same time.

 
 
  Published under free license. Design by Interspire