Challenge - 5 Problems
Union Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of union member assignment
What is the output of this C++ code snippet?
C++
#include <iostream>
union Data {
int i;
float f;
};
int main() {
Data d;
d.i = 65;
std::cout << d.i << " " << d.f << std::endl;
return 0;
}Attempts:
2 left
💡 Hint
Remember that union members share the same memory space.
✗ Incorrect
Assigning to one member of a union changes the shared memory. Reading another member interprets the same bits differently, so the float value is a strange small number.
❓ Predict Output
intermediate2:00remaining
Size of union vs struct
What is the output of this C++ code?
C++
#include <iostream>
union U {
int i;
double d;
};
struct S {
int i;
double d;
};
int main() {
std::cout << sizeof(U) << " " << sizeof(S) << std::endl;
return 0;
}Attempts:
2 left
💡 Hint
Union size is the size of its largest member; struct size is sum plus padding.
✗ Incorrect
Union size equals the largest member size (double = 8 bytes). Struct size is sum of members plus padding (int 4 + padding 4 + double 8 = 16).
🔧 Debug
advanced2:00remaining
Why does this union code cause undefined behavior?
Consider this code snippet. What is the main reason it causes undefined behavior?
C++
#include <iostream>
union U {
int i;
float f;
};
int main() {
U u;
u.i = 10;
std::cout << u.f << std::endl;
u.f = 3.14f;
std::cout << u.i << std::endl;
return 0;
}Attempts:
2 left
💡 Hint
Think about what happens when you read a union member different from the last one written.
✗ Incorrect
In C++, reading a union member other than the one most recently written is undefined behavior, even if it compiles and runs.
🧠 Conceptual
advanced2:00remaining
Union member initialization in C++17 and later
Which statement about union member initialization in C++17 and later is correct?
Attempts:
2 left
💡 Hint
C++17 introduced changes to allow in-class member initializers in unions.
✗ Incorrect
Since C++17, unions can have members with in-class initializers, allowing direct initialization of union members.
❓ Predict Output
expert3:00remaining
Output of union with anonymous struct and bitfields
What is the output of this C++ code?
C++
#include <iostream>
union U {
struct {
unsigned int a : 3;
unsigned int b : 5;
} bits;
unsigned char byte;
};
int main() {
U u{};
u.byte = 0b10101100;
std::cout << u.bits.a << " " << u.bits.b << std::endl;
return 0;
}Attempts:
2 left
💡 Hint
Bitfields pack bits starting from least significant bit; check binary representation carefully.
✗ Incorrect
The byte 0b10101100 has bits: 1 0 1 0 1 1 0 0 (MSB to LSB). bits.a uses 3 LSB bits (100 binary = 4 decimal), bits.b uses next 5 bits (10101 binary = 21 decimal).