Considering the efforts it goes to add include guards to each header file and the added possibilities of errors they introduce (e.g. using the same macro name in more than one file), why are they not build into the language as default behaviour?
What language design tradeoffs have lead to this decision by the makers of C/C++ standards?
Are there any practical benefits for being able to include files multiple times?
In some cases, you want to include the same header several times, for different purposes.
Are there any practical benefits for being able to include files multiple times?
Of course yes. Read also about X-macros.
For example, you are defining some enum
for colors.
You could have a myenum.h
header with
// file myenum.h included several times
MYENUM(red)
MYENUM(blue)
MYENUM(yellow)
(and you could imagine hundreds of other colors there, that you don't want to repeat)
then, in your main.c
file (or in some guarded header file), you declare that enum using:
enum color_en {
#define MYENUM(X) X,
#include "myenum.h"
#undef MYENUM
};
and in the same main.c
file, you later have a printing routine:
void print_color(enum color_en col) {
switch (col) {
#define MYENUM(X) case X: puts(#X); break;
#include "myenum.h"
#undef MYENUM
default: puts("???"); break;
}
}
Read the documentation of cpp
. The #X
above is stringizing X
Notice that even with modern C++, doing the same with templates is surprisingly difficult (or still impossible).
I am surprised people are not taught more about such useful tricks. Of course, you probably want to add more comments to keep your code readable.
PS. Notice that C preprocessing and its macros is profoundly (and sadly) textual - designed as string rewriting. Common Lisp and Terra and Rust macros show that other approaches are possible (they view their macro system as manipulation of ASTs).