Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does it mean by saying that union members can only be manipulted one at a time?

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:).

like image 758
JK electronic Avatar asked Oct 15 '25 14:10

JK electronic


1 Answers

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:

  • the compiler could detect the problem and raise a warning or error (but it is not required to...)
  • writeln(result.marks) could write 90 or the code of the 'a'character (97) or nothing, or something else of even end the program

And 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...

like image 60
Serge Ballesta Avatar answered Oct 18 '25 18:10

Serge Ballesta