C - Union
Learn C - C tutorial - C union - C examples - C programs
C Union - Definition and Usage
- Union and structure in C - Programming are same in concepts, except allocating memory for their members.
- Structure allocates storage space for all its members separately.
- Whereas, Union allocates one common storage space for all its members.
- We can access only one member of union at a time.
- We can’t access all member values at the same time in union.
- But, structure can access all member values at the same time.
- This is because, Union allocates one common storage space for all its members. Whereas Structure allocates storage space for all its members separately.
C Syntax
Sample - C Code
C Code - Explanation
- In this statement we create the union with its union name as “number” where the union contain different data types.
- Here in this statement we create a variable for accessing a union element whose union variable name is “x” .
- In this statement we get the value for the variable “n1” with its union variable name by printing the value.
- In this statement we get the value for the variable “n2” with its union variable name by printing the value.
Sample Output - Programming Examples
- Here in this output we get the integer value for the variable “n1” where its value “24” has been displayed here.
- Here in this output we get the float value for the variable “n2” where its value “34.500000” has been displayed here..