Using a union for type punning is non-portable (though not particularly less portable than any other method of type punning).
OTOH, a parser, for one example, typically has a union to represent values in expressions.
[Edit: I'm replacing the parser example with one I hope is a bit more understandable]:
Let's consider a Windows resource file. You can use it to define resources like menus, dialogs, icons, etc. Something like this:
#define mn1 2
mn1 MENU
{
MENUITEM "File", -1, MENUBREAK
}
ico1 "junk.ico"
dlg1 DIALOG 100, 0, 0, 100, 100
BEGIN
FONT 14, "Times New Roman"
CAPTION "Test Dialog Box"
ICON ico1, 700, 20, 20, 20, 20
TEXT "This is a string", 100, 0, 0, 100, 10
LTEXT "This is another string", 200, 0, 10, 100, 10
RTEXT "Yet a third string", 300, 0, 20, 100, 10
LISTBOX 400, 20, 20, 100, 100
CHECKBOX "A combobox", 500, 100, 100, 200, 10
COMBOBOX 600, 100, 210, 200, 100
DEFPUSHBUTTON "OK", 75, 200, 200, 50, 15
END
Parsing a the MENU gives a menu-definition; parsing the DIALOG gives a dialog definition and so on. In the parser we represent that as a union:
%union {
struct control_def {
char window_text[256];
int id;
char *class;
int x, y, width, height;
int ctrl_style;
} ctrl;
struct menu_item_def {
char text[256];
int identifier;
} item;
struct menu_def {
int identiifer;
struct menu_item_def items[256];
} mnu;
struct font_def {
int size;
char filename[256];
} font;
struct dialog_def {
char caption[256];
int id;
int x, y, width, height;
int style;
struct menu_def *mnu;
struct control_def ctrls[256];
struct font_def font;
} dlg;
int value;
char text[256];
};
Then we specify the type that will be produced by parsing a particular type of expression. For example, a font definition in the file becomes a font
member of the union:
%type <font> font
Just to clarify, the <font>
part refers to the union member that's produced and the second "font" refers to a parser rule that will yield a result of that type. Here's the rule for this particular case:
font: T_FONT T_NUMBER "," T_STRING {
$$.size = $2;
strcpy($$.filename,$4);
};
Yes, in theory we could use a struct instead of a union here -- but beyond wasting memory, it just doesn't make sense. A font definition in the file only defines a font. It would make no sense to have it produce a struct that included a menu definition, icon definition, number, string, etc. in addition to the font it actually defines.
[end of edit]
Of course, using unions to save memory is rarely very important anymore. While it may generally seem rather trivial now, back when 64 Kb of RAM was a lot, the memory savings meant a lot more.
"C - A reference Manual", 5th Ed., Harbison/Steele
– Recountal