Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between a preprocessor macro with no arguments, and one with zero arguments

Is there any reason to prefer

#define MY_MACRO() ..stuff..

to

#define MY_MACRO ..stuff..

Don't use macros is not a valid answer...

like image 314
StephQ Avatar asked Nov 22 '10 22:11

StephQ


People also ask

What is difference between preprocessor and macros?

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.

What do you mean by macros with arguments?

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.

What is the difference between a macro and the preprocessor directives used in C?

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.

How many arguments can a macro have?

For portability, you should not have more than 31 parameters for a macro. The parameter list may end with an ellipsis (…).


3 Answers

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.

like image 53
James McNellis Avatar answered Oct 22 '22 15:10

James McNellis


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.

like image 33
Victor Zamanian Avatar answered Oct 22 '22 14:10

Victor Zamanian


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 ...

like image 1
Goz Avatar answered Oct 22 '22 14:10

Goz