16

If a #define is used with no value, like

#define COMMAND_SPI()

does it take value 0 by default?

4
  • 3
    What exactly stopped you from just running the preprocessor yourself and seeing what happens? Commented Jun 12, 2014 at 23:05
  • Note that you've defined a function-like macro, which means that COMMAND_SPI won't be expanded unless it's followed by a parenthesized argument list. Commented Jun 12, 2014 at 23:18
  • 3
    @KerrekSB one system's behaviour in one test case does not guarantee that all systems behave the same (or even that the same code behaves the same when re-run on the same system) Commented Jun 13, 2014 at 0:16
  • @MattMcNabb: On the other hand, observing even one conforming system not replacing the macro with 0 would have immediately destroyed the OP's hypothesis. Commented Jun 13, 2014 at 0:55

1 Answer 1

22

No, it evaluates to nothing. Literally the symbol gets replaced with nothing.

However, once you have #define FOO, the preprocessor conditional #ifdef FOO will now be true.

Note also that in gcc and possibly other compilers, if you define a macro with -DFOO on the command line, that evaluates to 1 by default.


Since the OP updated his question to reference function-like macros, let's consider a small example.

#define FOO
#define BAR()


FOO
BAR
BAR()

This is not a valid C program, but the preprocessor does not care. If I compile this with gcc -E Input.c, I get a blank, followed by BAR followed by another blank. This is because the first and third expressions evaluate to nothingness, and the middle expression is not expanded because there are no () after it.

Sign up to request clarification or add additional context in comments.

3 Comments

That last paragraph is compiler-specific; gcc behaves that way, but it's not specified by the language. For gcc and similar compilers, you can do the equivalent of #define FOO by passing -DFOO= on the command line.
@KeithThompson, Thanks for the caveat. I'll fold it into the answer.
Note that POSIX requires c99 provide the -D behaviour: -D name[=value] Define name as if by a C-language #define directive. If no = value is given, a value of 1 shall be used. The -D option has lower precedence than the -U option. That is, if name is used in both a -U and a -D option, name shall be undefined regardless of the order of the options. Additional implementation-defined names may be provided by the compiler. Implementations shall support at least 2048 bytes of -D definitions and 256 names.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.