Alex Rivera | Logout

Empty function macros

Asked 2012-02-08T03:50:52.003
48

If I define a function macro with no actual body, is it like an empty string with the compiler (i.e. It doesn't generate any extra instructions at compile time)?

Example:

#define SomeMacro(a)

SomeMacro("hello"); // This line doesn't add any instructions, does it?
Edit
Report

2 Answers

34

Your code is not totally correct, I suggest you to put empty braces in your macro

#define somemacro(a) {}

the reason is simple, you code will be much more safe!

take this example:

if(Value)
    somemacro(a)
else
    somemacro(b)

If the macro is empty, your code will not compile! (Expected primary-expressione before "else"). Anyway certain style rules force you to write

if(Value)
{
    somemacro(a)
}
else
{
    somemacro(a)
}

so that will not be a problem.

Another option is to use ";" instead of "{}" but that option in the same case will give you compile time warnings, while empty braces will not give warnings nor errors! (semicolon is still better even if give warnings) ;)

take following case

if(value)
    somemacro(a);
else
    somemacro(b);

will expand to

if(value)
{};
else
{};

that can't compile!

That's why macros are evil

(since macros are simple text-replacement, the rule of dumbs should be to always try to manually replace the code and see what happens, there are also tools that will replace macros for you showing the expanded code.)

Still guessin if there is a macro that is totally safe? Yes it is called "NOP"

#define somemacro(a) ((void)0)

that will work in any case (even source files of compilers use that as NOP, for example just look at "assert.h"

answered 2012-12-26T16:08:04.557
7

That's correct. Your code expands to

;

after preprocessing.

Note that you can ask your compiler to show you the code after preprocessing (in gcc, this is the -E option; your compiler may vary).

answered 2012-02-08T03:53:31.883

Your Answer