Interview Questions

Can I initialize unions?

C Interview Questions and Answers


(Continued from previous question...)

Can I initialize unions?

In the original ANSI C, an initializer was allowed only for the first-named member of a union. C99 introduces ``designated initializers'' which can be used to initialize any member.

In the absence of designated initializers, if you're desperate, you can sometimes define several variant copies of a union, with the members in different orders, so that you can declare and initialize the one having the appropriate first member. (These variants are guaranteed to be implemented compatibly, so it's okay to ``pun'' them by initializing one and then using the other.)

(Continued on next question...)

Other Interview Questions