I was just reading up on the theory behind unions and stacks. The book (Object Orientated Programming with C++ by E Balagurusamy) said that "members of a union can only be manipulated one at a time". But I was messing around with unions. I did this with no error.
#include <iostream>
#include <iomanip>
#include "ConsoleApplication1.h"
using namespace std;
//user defined data types
#define writeln(x)(cout<<x<<endl)
union result
{
int marks;
char grade;
float percent;
};
int main()
{
result result;
result.marks = 90;
result.grade = 'a';
writeln(result.grade);
writeln(result.marks);
}
So may you please clarify what that statement meant. Thanks:).
It means that you are invoking Undefined Behaviour. Let us see what happen of each line of code:
result result; // ok, you have declared an union
result.marks = 90; // ok, result.marks is defined
result.grade = 'a'; // ok, result.grade is defined, but result.mark is no longer
writeln(result.grade); // ok, access to the last written member of the union
writeln(result.marks); // UB: access to a member which is not the last writter
UB is really unfriendly for newcomers, because anything can happen:
writeln(result.marks) could write 90 or the code of the 'a'character (97) or nothing, or something else of even end the programAnd as anything can happen, you can get the expected behaviour on one run, and later get a different one.
Long story made short: do not play with that...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With