Bird
Raised Fist0
Cprogramming~20 mins

Union basics - Practice Problems & Coding Challenges

Choose your learning style10 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 program?
C
#include <stdio.h>

union Data {
    int i;
    float f;
    char str[20];
};

int main() {
    union Data data;
    data.i = 10;
    data.f = 220.5f;
    printf("%d\n", data.i);
    return 0;
}
ASome unpredictable integer value
B220
C10
DCompilation error
Attempts:
2 left
💡 Hint
Remember that all members of a union share the same memory space.
❓ Predict Output
intermediate
2:00remaining
Size of union vs struct
What will be the output of this program?
C
#include <stdio.h>

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

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

int main() {
    printf("%zu %zu\n", sizeof(union U), sizeof(struct S));
    return 0;
}
A16 24
B16 16
C8 16
D24 24
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 unexpected output?
Consider this code snippet. Why does printing data.str after assigning data.i show unexpected characters?
C
#include <stdio.h>
#include <string.h>

union Data {
    int i;
    char str[4];
};

int main() {
    union Data data;
    data.i = 0x41424344; // Hex for 'ABCD'
    printf("%s\n", data.str);
    return 0;
}
ABecause the integer value is too large to fit in the union
BBecause the string is not null-terminated, printf reads beyond the array causing garbage output
CBecause union members cannot be accessed after assignment to another member
DBecause printf cannot print char arrays inside unions
Attempts:
2 left
💡 Hint
Think about how strings are represented in C and what printf expects.
🧠 Conceptual
advanced
2:00remaining
Union member alignment and padding
Which statement about union member alignment and padding is true?
AUnion size is always the sum of all member sizes including padding
BUnion members are stored in separate memory locations to avoid padding
CUnion size is the size of its largest member, aligned to the strictest member's alignment requirement
DUnion size is always equal to the smallest member size
Attempts:
2 left
💡 Hint
Think about how unions share memory and how alignment affects size.
❓ Predict Output
expert
2:00remaining
Output of union with bit fields and overlapping members
What is the output of this program?
C
#include <stdio.h>

union U {
    struct {
        unsigned int a:4;
        unsigned int b:4;
    } bits;
    unsigned char byte;
};

int main() {
    union U u;
    u.byte = 0;
    u.bits.a = 9;  // 1001 in binary
    u.bits.b = 6;  // 0110 in binary
    printf("%u\n", u.byte);
    return 0;
}
ACompilation error
B150
C90
D105
Attempts:
2 left
💡 Hint
Calculate the bits: a in lower 4 bits, b in upper 4 bits.

Practice

(1/5)
1. What is the main characteristic of a union in C?
easy
A. Unions can only store integers
B. Each member has its own separate memory
C. All members share the same memory location
D. Unions automatically initialize all members

Solution

  1. Step 1: Understand union memory sharing

    A union allocates one shared memory block for all its members, so they overlap.
  2. Step 2: Compare with struct memory allocation

    Unlike structs, unions do not allocate separate memory for each member.
  3. Final Answer:

    All members share the same memory location -> Option C
  4. Quick Check:

    Union memory sharing = All members share the same memory location [OK]
Hint: Remember: union members overlap in memory [OK]
Common Mistakes:
  • Thinking each member has separate memory
  • Assuming unions initialize all members
  • Believing unions only store one data type
2. Which of the following is the correct way to define a union named Data with an int and a float member?
easy
A. union Data { int i; float f; };
B. struct 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', the name, and braces with members inside.
  2. Step 2: Check each option

    union Data { int i; float f; }; uses correct syntax with braces and semicolons. Options A, B, and C have syntax errors or wrong keywords.
  3. Final Answer:

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

    Correct union syntax = union Data { int i; float f; }; [OK]
Hint: Use 'union Name { members; };' syntax [OK]
Common Mistakes:
  • Using struct instead of union
  • Using parentheses instead of braces
  • Assigning values in the definition
3. What will be the output of the following C code?
union Number {
  int i;
  float f;
};

int main() {
  union Number num;
  num.i = 65;
  printf("%c", num.f);
  return 0;
}
medium
A. A
B. 65
C. Compilation error
D. Undefined behavior or garbage character

Solution

  1. Step 1: Understand union member sharing

    Setting num.i = 65 stores integer bits in union memory.
  2. Step 2: Printing num.f as char

    Printing num.f with %c treats float bits as a char, causing unpredictable output.
  3. Final Answer:

    Undefined behavior or garbage character -> Option D
  4. Quick Check:

    Accessing different union member types = Undefined behavior or garbage character [OK]
Hint: Accessing different union members can cause garbage output [OK]
Common Mistakes:
  • Expecting integer 65 to print as 'A'
  • Assuming union members convert automatically
  • Ignoring type mismatch in printf
4. Identify the error in this union usage:
union Data {
  int i;
  float f;
};

int main() {
  union Data d;
  d.i = 10;
  d.f = 3.14;
  printf("%d", d.i);
  return 0;
}
medium
A. Using %d to print a union member is invalid
B. Assigning to d.f overwrites d.i value
C. Cannot assign to multiple union members sequentially
D. Union must be initialized before use

Solution

  1. Step 1: Analyze assignments to union members

    Assigning d.i then d.f means d.f overwrites the same memory used by d.i.
  2. Step 2: Understand printf output

    Printing d.i after assigning d.f prints the overwritten value, not 10.
  3. Final Answer:

    Assigning to d.f overwrites d.i value -> Option B
  4. Quick Check:

    Union members share memory, last assignment wins = Assigning to d.f overwrites d.i value [OK]
Hint: Last assigned union member overwrites previous values [OK]
Common Mistakes:
  • Thinking union members hold values independently
  • Believing %d cannot print union members
  • Assuming union needs initialization
5. You want to store either an int, a float, or a char in the same memory space and print the stored value correctly. Which approach using a union and an additional variable is best?
hard
A. Use a union for data and an enum to track the active member type
B. Use a union and print all members every time
C. Use separate variables for each type without union
D. Use a union and always print the int member

Solution

  1. Step 1: Understand union limitation

    Union stores one member at a time, so we must know which member is active.
  2. Step 2: Use enum to track active member

    An enum variable can track which type is stored, so printing uses correct format.
  3. Final Answer:

    Use a union for data and an enum to track the active member type -> Option A
  4. Quick Check:

    Union + enum for type tracking = Use a union for data and an enum to track the active member type [OK]
Hint: Track active union member with enum for correct printing [OK]
Common Mistakes:
  • Printing all union members blindly
  • Not tracking which member is active
  • Using separate variables wastes memory
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