Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining something to itself in C preprocessor

I ran into these lines:

#define bool  bool
#define false false
#define true  true

I don't think I need to say more than "wtf?", but just to be clear: What is the point of defining something to itself?

The lines come from clang stdbool.h

like image 955
klutt Avatar asked Oct 17 '17 19:10

klutt


2 Answers

The C and C++ standards explicitly allow that (and requires that there is no infinite expansion)

BTW, function-like recursive (or self-refential) macros are even more useful:

#define puts(X) (nblines++,puts(X))

(the inner puts is a call to the standard puts function; the macro "overloads" such further calls by counting nblines)

Your define could be useful, e.g. with later constructs like #ifdef true, and it can't be a simple #define true because that would "erase" every further use of true, so it has to be exactly#define true true.

like image 149
Basile Starynkevitch Avatar answered Sep 28 '22 02:09

Basile Starynkevitch


It allows the user code to conditionally compile based on whether those macros are or aren't defined:

#if defined(bool)
    /*...*/
#else
    /*...*/
#endif

It basically saves you from having to pollute the global namespace with yet another name (like HAVE_BOOL), provided that the implementation lets its users know that iff it provides a bool, it will also provide a macro with the same name that expands to it (or the implementation may simply use this internally for its own preprocessor conditionals).

like image 42
PSkocik Avatar answered Sep 28 '22 03:09

PSkocik