0
0
C++programming~20 mins

Union basics in C++ - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Union Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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;
}
ACompilation error
B65 65
C0 0
D65 9.1e-44
Attempts:
2 left
💡 Hint
Remember that union members share the same memory space.
Predict Output
intermediate
2: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;
}
A12 12
B16 8
C8 16
D8 8
Attempts:
2 left
💡 Hint
Union size is the size of its largest member; struct size is sum plus padding.
🔧 Debug
advanced
2: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;
}
AReading a different union member than the one last written causes undefined behavior.
BUnion members cannot be assigned values directly.
CThe union must have a constructor to be used.
DThe code is missing a return statement.
Attempts:
2 left
💡 Hint
Think about what happens when you read a union member different from the last one written.
🧠 Conceptual
advanced
2:00remaining
Union member initialization in C++17 and later
Which statement about union member initialization in C++17 and later is correct?
AUnions must be initialized using a constructor only.
BYou can initialize a union member directly using an in-class initializer.
COnly the first member of a union can be initialized at declaration.
DUnions cannot have any member initialized at declaration.
Attempts:
2 left
💡 Hint
C++17 introduced changes to allow in-class member initializers in unions.
Predict Output
expert
3: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;
}
A4 21
B4 22
C5 21
D5 22
Attempts:
2 left
💡 Hint
Bitfields pack bits starting from least significant bit; check binary representation carefully.