According the standard macro redefinition is prohibited without using #undef before:
But the following redefinitions are invalid:
#define OBJ_LIKE (0) // different token sequence #define OBJ_LIKE (1 - 1) // different whitespace
At the same time it's allowed to #undef for macros that were not defined at all before:
It is ignored if the specified identifier is not currently defined as a macro name.
I'm interested what is the rationale for this, i.e. forbidding redefinition without #undef in the middle? Some compiler optimization purposes or what?
Because it was inherited from C.
ISO/IEC 9899:1990 §6.8.3 (AKA C90) contains similar wording:
And looking at N802 produced by WG14 (https://www.open-std.org/jtc1/sc22/wg14/www/docs/n802.pdf) "Rationale for International Standard - Programming Language - C" §6.8.3, the reason is stated as:
So "benign" redefinitions are encouraged, where the alternative would be something like:
Simply
#define SPEED_OF_LIGHT 299792458will generate a warning if another header defines it differently.And a similar thing for
#undef. The rationale given for §6.8.3.5:Where §7.1.8 of C99 / §7.1.7 of C90 says:
For example, a standard library header might have
double abs(double);as well as#define abs(x) _BUILTIN_abs(x), and#undef abswas legal and allowed you to make sureabsreferred to a bona fide function.Of course, this doesn't apply to C++, where standard library functions cannot be macros. But the other rationale ("It is explicitly permitted to
#undefa macro that has no current definition") still applies, i.e., "the committee says so".