Interview Questions
Structures, Unions, Enums · Study material
C Structures, Unions and Enums Interview Questions
1. What is the difference between a structure and a union?
Structure members have separate storage; union members overlap at the same address. A struct is at least the sum of its members, a union is the size of its largest member.
2. What is structure padding, and how do you reduce it?
Unused bytes the compiler inserts so each member is correctly aligned. Order members from largest to smallest alignment; compiler-specific packing (__attribute__((packed))) removes it at the cost of slower or unaligned access.
3. Why can't you compare two structures with ==?
C does not define == for structs. memcmp() is unreliable too, because padding bytes can hold any value. Compare the members.
4. What is the difference between . and ->?
. selects a member of a struct object; -> selects a member through a pointer: p->x means (*p).x.
5. What is a self-referential structure?
A struct that contains a pointer to its own type, like a linked-list node. It cannot contain an object of its own type, which would be infinitely large.
6. What is a flexible array member?
A last member declared as type name[];. Memory for it is allocated together with the struct, so variable-length data sits right after the header in one block.
7. What is a tagged union?
A struct that holds an enum tag and a union; the tag tells which union member is currently valid. It is how C stores values of several types safely.
8. What are bit-fields, and what are their limits?
Members with a width in bits, such as unsigned flag : 1. You cannot take their address, and their layout in memory is implementation-defined.
9. What values do enum constants get?
The first is 0 unless given a value; each next one is the previous plus 1. Enum constants are of type int (C23 allows a different fixed type).
10. What does typedef struct point Point; do?
It creates the alias Point for struct point, so you can write Point p; instead of struct point p;.
11. Is assigning one struct to another a deep copy?
No. Every member is copied, but a pointer member is copied as an address, so both structs point to the same data.
12. What do anonymous structs and unions (C11) give you?
Members of an unnamed nested struct or union are accessed as if they belonged to the outer struct: v.i instead of v.u.i.