0
0
C++programming~20 mins

Structure vs union comparison in C++ - Practice Questions

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Structure vs Union Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of structure size and member values
What is the output of this C++ code?
C++
#include <iostream>
using namespace std;

struct Data {
    int i;
    char c;
    double d;
};

int main() {
    Data data = {10, 'A', 3.14};
    cout << sizeof(data) << " ";
    cout << data.i << " " << data.c << " " << data.d << endl;
    return 0;
}
A41.3 A 01 42
B24 10 A 3.14
C24 0 A 3.14
D16 10 A 0
Attempts:
2 left
💡 Hint
Remember that structure size includes padding for alignment.
Predict Output
intermediate
2:00remaining
Output of union member values after assignment
What is the output of this C++ code?
C++
#include <iostream>
using namespace std;

union Data {
    int i;
    char c;
    double d;
};

int main() {
    Data data;
    data.i = 10;
    data.c = 'A';
    cout << data.i << " " << data.c << endl;
    return 0;
}
A65 10
B10 A
C10 10
D65 A
Attempts:
2 left
💡 Hint
In a union, all members share the same memory location.
🧠 Conceptual
advanced
1:30remaining
Difference in memory allocation between struct and union
Which statement correctly describes the difference in memory allocation between a structure and a union in C++?
AA structure allocates memory for all members separately; a union allocates memory equal to its largest member only.
BA union allocates memory for all members separately; a structure allocates memory equal to its largest member only.
CBoth structure and union allocate memory equal to the sum of all members' sizes.
DBoth structure and union allocate memory equal to the size of their smallest member.
Attempts:
2 left
💡 Hint
Think about how members share memory in a union.
Predict Output
advanced
1:30remaining
Output of modifying union members
What is the output of this C++ code?
C++
#include <iostream>
using namespace std;

union Data {
    int i;
    float f;
};

int main() {
    Data data;
    data.i = 1065353216; // bit pattern for float 1.0
    cout << data.f << endl;
    return 0;
}
A1
B0
C1065353216
DUndefined behavior
Attempts:
2 left
💡 Hint
The int value corresponds to the bit pattern of float 1.0.
🧠 Conceptual
expert
2:00remaining
Why use union over struct in embedded systems?
Why might a programmer prefer using a union instead of a structure in embedded systems programming?
ATo ensure each member has its own separate memory for thread safety.
BTo allow simultaneous storage of multiple data types for faster access.
CTo save memory by overlapping storage of different data types that are never used simultaneously.
DTo automatically initialize all members to zero.
Attempts:
2 left
💡 Hint
Think about limited memory in embedded devices.