What happens when #define is used without string replacement?
While trying to debug my code, I noted a few printf
like this:
#if debug
printf(...);
#endif
And at the beginning of the file, I mistakenly wrote #define debug
instead#define debug 1
gcc throws the following error:
error: #if without expression
Now I have 2 options:
- change of definition in
#define debug 1
- changing if in
#ifdef debug
I know that after seeing #define debug 1
PP will replace every one debug
in my code with 1
and that why it does #if debug
n't work in my code - the compiler doesn't see the expression ...
My question is when I use #ifdef debug
- what happens? I believe debug
it is saved and verified somewhere, but where and how?
source to share
It's actually quite simple: #define debug
it makes the definition debug
empty. It is still defined. An empty macro is different from one that does not exist. #undef debug
will remove the macro.
#ifdef
doesn't care about the value. It checks if the macro is not defined. If you don't care about the value, always use #ifdef
.
source to share
The corresponding syntax for the preccessing directive is #define
outlined in ยง6.10 ยถ1 (C11 Draft Standard):
# define replacement-list identifier new-line
...
List of notes: pp-tokens opt
The semantics of the directive are #define
found in ยง6.10.3 :
Form preprocessing directive
# define replacement-list identifier new-line
defines an object-like macro that invokes each subsequent instance of the macro name, which will be replaced with a replacement list of preprocessing tokens that make up the remainder of the directive. The substitution list is then re-scanned for more of the macro names listed below.
Note that the override list does not necessarily consist of preprocessing tokens and therefore can be empty. So, consider a notable example from the Standard :
#define EMPTY
Since, according to ยง6.10.3 ยถ7 :
The identifier following define is called name by the macro. There is one namespace for macro names.
the macro name is EMPTY
defined and exists in the namespace for macro names. Each subsequent instance EMPTY
will be replaced without preprocessing tokens.
source to share