Is there any reason to prefer
#define MY_MACRO() ..stuff..
to
#define MY_MACRO ..stuff..
Don't use macros is not a valid answer...
macros are name for fragment of code. A macro processor is a program that copies a stream of text from one place to another, making a systematic set of replacements as it does so. ... A preprocessor is a program that processes its input data to produce output that is used as input to another program.
Function-like macros can take arguments, just like true functions. To define a macro that uses arguments, you insert parameters between the pair of parentheses in the macro definition that make the macro function-like. The parameters must be valid C identifiers, separated by commas and optionally whitespace.
Macro: a word defined by the #define preprocessor directive that evaluates to some other expression. Preprocessor directive: a special #-keyword, recognized by the preprocessor. Show activity on this post. preprocessor modifies the source file before handing it over the compiler.
For portability, you should not have more than 31 parameters for a macro. The parameter list may end with an ellipsis (…).
Replacement only occurrs for a function-like macro if the macro name is followed by a left parenthesis. So, the following all invoke the function-like macro MY_MACRO()
:
MY_MACRO()
MY_MACRO ( )
MY_MACRO
( )
But this would not:
MY_MACRO SomethingElse
It depends on how you are using the macro and what it is used for as to whether or not this is important. Ideally, your macros will all have distinct names; if you reserve all-uppercase identifiers for macros, then it shouldn't matter whether you use an object-like or a function-like macro with zero parameters.
Aesthetically, it's usually (but not always) cleaner not to have function-like macros that take zero parameters.
I prefer to use MY_MACRO()
, with parentheses, because it feels more like I'm calling a function. Otherwise it looks like I'm calling a constant:
MY_MACRO();
vs
MY_MACRO;
That is if the definition is used to call code, rather than just a simple constant value.
Macro( x ) is preferrable when you have parameters to pass. If you are doing a simple "replace" then, IMO, its preferrable to use #define BLAH ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With