Bird
Raised Fist0
C++programming~20 mins

Structure vs union comparison in C++ - Practice Questions

Choose your learning style10 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.

Practice

(1/5)
1. Which of the following best describes the main difference between a struct and a union in C++?
easy
A. A struct stores all members separately; a union shares memory among members.
B. A struct shares memory among members; a union stores all members separately.
C. Both struct and union store members separately but differ in syntax.
D. Both struct and union share memory but differ in member access.

Solution

  1. Step 1: Understand memory allocation in struct

    A struct allocates separate memory for each member, so all members can hold values simultaneously.
  2. Step 2: Understand memory allocation in union

    A union shares the same memory space for all members, so only one member can hold a valid value at a time.
  3. Final Answer:

    A struct stores all members separately; a union shares memory among members. -> Option A
  4. Quick Check:

    Struct = separate memory, Union = shared memory [OK]
Hint: Struct = all values stored; Union = one value stored [OK]
Common Mistakes:
  • Thinking union stores all members separately
  • Confusing struct and union memory sharing
  • Assuming both have same memory behavior
2. Which of the following is the correct syntax to define a union named Data with an int and a float member?
easy
A. struct Data { int i; float f; };
B. union Data ( int i; float f; );
C. union Data { int i; float f; };
D. union Data = { int i; float f; };

Solution

  1. Step 1: Recall union syntax

    The correct syntax uses the keyword union, followed by the name, and braces enclosing members separated by semicolons.
  2. Step 2: Check each option

    union Data { int i; float f; }; matches correct syntax. struct Data { int i; float f; }; uses struct, not union. union Data ( int i; float f; ); uses parentheses instead of braces. union Data = { int i; float f; }; uses an assignment which is invalid.
  3. Final Answer:

    union Data { int i; float f; }; -> Option C
  4. Quick Check:

    Union syntax = keyword + braces + members [OK]
Hint: Use braces {} with union keyword for definition [OK]
Common Mistakes:
  • Using struct keyword instead of union
  • Using parentheses instead of braces
  • Trying to assign values in definition
3. What will be the output of the following C++ code?
union Number {
  int i;
  float f;
};

int main() {
  Number n;
  n.i = 65;
  std::cout << n.f << std::endl;
  return 0;
}
medium
A. A floating-point number representing the bit pattern of 65
B. 0
C. 65
D. Compilation error

Solution

  1. Step 1: Understand union memory sharing

    Assigning 65 to n.i stores the integer bits in the shared memory.
  2. Step 2: Interpret bits as float

    Printing n.f reads the same bits as a float, resulting in a floating-point number representing the bit pattern of 65, not the integer 65.
  3. Final Answer:

    A floating-point number representing the bit pattern of 65 -> Option A
  4. Quick Check:

    Union shares bits; reading different type shows bit pattern [OK]
Hint: Union members share bits; reading different type shows bit pattern [OK]
Common Mistakes:
  • Expecting integer 65 to print as float 65.0
  • Assuming union stores separate copies
  • Thinking code causes compilation error
4. Identify the error in the following code snippet:
struct Data {
  int x;
  union {
    int i;
    float f;
  } u;
};

int main() {
  Data d;
  d.x = 10;
  d.u.i = 20;
  d.u.f = 3.14;
  std::cout << d.x << ", " << d.u.i << std::endl;
  return 0;
}
medium
A. Cannot assign float to union member.
B. Accessing union member after assigning another member leads to undefined value.
C. Missing semicolon after union definition.
D. Struct cannot contain a union as a member.

Solution

  1. Step 1: Analyze union member assignments

    Assigning d.u.i = 20; then d.u.f = 3.14; overwrites the same memory because union members share memory.
  2. Step 2: Understand reading union members

    Reading d.u.i after assigning d.u.f gives an undefined or unexpected value because only the last assigned member is valid.
  3. Final Answer:

    Accessing union member after assigning another member leads to undefined value. -> Option B
  4. Quick Check:

    Union stores one value; reading old member is invalid [OK]
Hint: Only last assigned union member holds valid data [OK]
Common Mistakes:
  • Thinking struct cannot have union member
  • Ignoring union memory sharing rules
  • Expecting both union members to hold values simultaneously
5. You want to store either an integer ID or a floating-point score in a variable but never both at the same time, and you want to save memory. Which is the best approach in C++?
hard
A. Use a class with private int and float members.
B. Use a struct with both int and float members.
C. Use two separate variables, one int and one float.
D. Use a union with int and float members.

Solution

  1. Step 1: Understand memory needs

    Since only one value (int or float) is needed at a time, memory can be saved by sharing storage.
  2. Step 2: Choose union for shared memory

    A union allows storing either int or float in the same memory space, saving memory compared to a struct which stores both separately.
  3. Step 3: Evaluate other options

    Using two separate variables wastes memory. A class with private members behaves like struct in memory. Struct stores both values simultaneously, using more memory.
  4. Final Answer:

    Use a union with int and float members. -> Option D
  5. Quick Check:

    Union saves memory when only one value needed [OK]
Hint: Use union to save memory when storing one of many types [OK]
Common Mistakes:
  • Choosing struct and wasting memory
  • Using separate variables unnecessarily
  • Confusing class with memory optimization
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard