A note on using Unions
Related Blog Items
- Unions in C++
- IEEE 754 Binary Floating Point Representation
- L-Value and R-Value Expressions
- How to inlcude C header files in C++
- C, C++, Programming, Data Structures Quizzes
Consider the following program -
#include <stdio.h>
int
main ( void )
{
union {
int _i;
float _f;
}_u = { 10 };
printf ( "%f\n", u.f );
return 0;
}
Keep the following points on how a union object is represented in the memory:
- The size of an union object is equal to size of it’s largest member.
- Address of every member of an union object is same.
- A union can not have an instance of itself, but a pointer to instance of itself.
Let me introduce two terms: Object Representation and Object Interpretation.
Simply speaking, object representation is the pattern of bits of an object in the storage unit. And, object interpretation is the meaning of the representation.
In the above example, union members _i and _f reside in the same memory location, say M. The union object _u has been initialized to 10 which by default is assigned to the first member of the union. Since _i and _f has the same location, their object representation is also the same, but their interpretation would be different. Let us assume that a C implementation (i.e., compiler) uses 2’s complement for integers and IEEE 754 floating point format for float. Though, the bit pattern for _i and _f appear identical in the storage unit, their interpretation is different. Hence, if you thought that the above printf would print 10.000000, then you are wrong. The output of this program is unspecified.
Popularity: 6%
You need to log on to convert this article into PDF
Related Blog Items - Unions in C++
- IEEE 754 Binary Floating Point Representation
- L-Value and R-Value Expressions
- How to inlcude C header files in C++
- C, C++, Programming, Data Structures Quizzes
Related Blog Items
- Unions in C++
- IEEE 754 Binary Floating Point Representation
- L-Value and R-Value Expressions
- How to inlcude C header files in C++
- C, C++, Programming, Data Structures Quizzes
No Comments
No comments yet.