When a macro is created but no value is assigned, is there a default value? #define MACRO (end of line).
Macro definition has the syntax: #define <IDENTIFIER> <value>. Even if we don't pass a value, the macro is created, which can be verified by the following the program:
#include <stdio.h>
#define MACRO
int main() {
#ifdef MACRO
printf("MACRO was created");
#endif
return 0;
}
Also, if an identifier was not declared using #define but passed as the condition for #ifdef <IDENTIFIER>, the compiler treats the identifier as though it were the constant zero (false), which can be verified by the following the program:
#include <stdio.h>
int main()
{
#ifdef A
printf("No print but valid condition");
#endif
return 0;
}
Which doesn't print anything, but there are no warnings nor errors from the compiler.
My question is, when a macro is created but no value is assigned, is there a default value?
Consider the program:
#include <stdio.h>
#define MACRO
int main()
{
#if defined MACRO
printf("%d", MACRO);
#endif
return 0;
}
get the error message:
error: expected expression before ‘)’ token
Which would compile if we assign a value:
#include <stdio.h>
#define MACRO 3
int main()
{
#ifdef MACRO
printf("%d", MACRO);
#endif
return 0;
}
My guess is that #define MACRO doesn't assign any value, even though #ifdef will treat not-defined macros as 0 (or a false condition); Is that correct?
No, or yes? A macro defined without a replacement list like so:
expands to nothing, is removed from the processed input. Or the default value is nothing, an empty string, if you want to look at it that way.
No.
#ifdefonly cares about if defined or not defined. It doesn't care about the result of the expansion.#ifand#elifexpand the expression and treat undefined(!) tokens as 0.In other words,
#ifand#eliffirst expand all the macros, and then if there are any tokens that are not numbers or arithmetic operations, then those leftover tokens are replaced by 0.You may want to read C11 standard 6.10.1p4 for the source, maybe it will clear things up:
expands to
printf("%d", );. The part, );is invalid, thus you get a syntax error.