fork(2) download
  1. #include <iostream>
  2.  
  3. union A {
  4. int i;
  5. double d;
  6. char c;
  7. }; // the whole union occupies max(sizeof(int), sizeof(double), sizeof(char))
  8.  
  9. int main()
  10. {
  11. A a = { 43 }; // initializes the first member, a.i is now the active member
  12. // at this point, reading from a.d or a.c is UB
  13. std::cout << "a.i = " << a.i << std::endl;
  14. a.c = 'a'; // a.c is now the active member
  15. // at this point, reading from i or d is UB but most compilers define this
  16. std::cout << "a.i = " << a.i << std::endl; // 97 most likely
  17. return 0;
  18. }
Success #stdin #stdout 0s 3140KB
stdin
Standard input is empty
stdout
a.i = 43
a.i = 97