Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it wrong to add preprocessor directives in a function-like macro?

Tags:

c++

c

macros

I know that my question is similar to this one or this one, but I find that it is not really the same and, more, the second one has not an answer accepted, I decided to ask if it is correct to add preprocessor directives when a function-like macro is called?

In my case I have a function-like macro:

#define FUNC_MACRO(a, b)  // do something with the variables 

and somewhere in the code I call it with specific difference if some other macro is defined:

// ... FUNC_MACRO(aVal #ifdef ANOTHER_MACRO                 + offset #endif // ANOTHER_MACRO            , bVal); // ... 

I tested on my machine (linux, with gcc 4.8) and it worked ok (with and without the preprocessor directives, and with and without ANOTHER_MACRO defined), but is it safe to do so?

I read the 16.3/9 paragraph from the answer of the first similar question, but is it true for my case too?

like image 580
sop Avatar asked Sep 16 '16 15:09

sop


People also ask

Are macros preprocessor directives?

There are 4 Main Types of Preprocessor Directives: Macros. File Inclusion. Conditional Compilation. Other directives.

Is macro and preprocessor same?

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.

Why use a macro instead of a function?

Speed versus size The main benefit of using macros is faster execution time. During preprocessing, a macro is expanded (replaced by its definition) inline each time it is used. A function definition occurs only once regardless of how many times it is called.


1 Answers

The C language leaves this as undefined behavior in 6.10.3 Macro replacement, ¶11:

If there are sequences of preprocessing tokens within the list of arguments that would otherwise act as preprocessing directives, the behavior is undefined.

So indeed it's wrong to do it.

GCC and perhaps other popular compiles don't catch it, which is probably why many users of the language are not aware. I encountered this when some of my code failed to compile on PCC (and promptly fixed the bug in my code).

Update: PJTraill asked in the comments for a case where it would be "misleading or meaningless" to have preprocessor directives inside a macro expansion. Here's an obvious one:

    foo(a, b, #ifdef BAR         c); #else         d); #endif 

I'm not sure whether it would have been plausible for the language to specify that balanced preprocessor conditionals inside the macro expansion are okay, but I think you'd run into problems there too with ambiguities in the order in which they should be processed.

like image 161
R.. GitHub STOP HELPING ICE Avatar answered Oct 14 '22 03:10

R.. GitHub STOP HELPING ICE