Interview Questions

What is the difference between a structure and a union, anyway?

C Interview Questions and Answers


(Continued from previous question...)

What is the difference between a structure and a union, anyway?

A union is essentially a structure in which all of the fields overlay each other; you can only use one field at a time. (You can also cheat by writing to one field and reading from another, to inspect a type's bit patterns or interpret them differently, but that's obviously pretty machine-dependent.) The size of a union is the maximum of the sizes of its individual members, while the size of a structure is the sum of the sizes of its members. (In both cases, the size may be increased by padding;

(Continued on next question...)

Other Interview Questions