0
0
Cprogramming~5 mins

Union basics - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a union in C?
A union is a special data type in C that allows storing different data types in the same memory location. Only one member can hold a value at a time.
Click to reveal answer
beginner
How does memory allocation work in a union?
The size of a union is equal to the size of its largest member because all members share the same memory space.
Click to reveal answer
intermediate
What happens if you assign a value to one member of a union and then read from another member?
Reading from a different member than the one last assigned can lead to unexpected or garbage values because all members share the same memory.
Click to reveal answer
beginner
Write a simple union declaration with an int and a float member.
Example:
union Number {
  int i;
  float f;
};
Click to reveal answer
intermediate
Why might you use a union instead of a struct?
You use a union to save memory when you know only one of several types will be used at a time, unlike a struct which allocates memory for all members.
Click to reveal answer
What is the size of a union with members: char c;, int i;, and double d;?
ASum of sizes of all members
BSize of <code>int</code>
CSize of <code>double</code>
DSize of <code>char</code>
If you store a value in one union member and then read from another, what is the result?
AUndefined or garbage value
BZero
CCompiler error
DThe value of the last stored member
Which keyword is used to declare a union in C?
Aunion
Bstruct
Cenum
Dtypedef
Why use a union instead of a struct?
ATo define functions
BTo store multiple values at once
CTo create arrays
DTo save memory when only one value is needed at a time
How do you access members of a union variable named u?
A<code>u->member</code>
B<code>u.member</code>
C<code>*u.member</code>
D<code>u:member</code>
Explain what a union is in C and how it differs from a struct.
Think about memory usage and how values are stored.
You got /3 concepts.
    Describe a situation where using a union would be more efficient than a struct.
    Consider saving memory in embedded systems or low-memory devices.
    You got /3 concepts.