Can I comment multi-line macros?

There is no way to use // comments in a macro except the last line of the macro.

As Paul R suggests, the /* comment */ does work and seems to be the only option:

#define SOME_BIG_MACRO(input)\
  SOME_FUNCTION_CALL()  /* this does... */ \
  SOME_OTHER_FUNCTION_CALL()

The reason is the following. Standard for Programming Language C ++ (I only have access to this draft) specifies that physical lines of the source file can be concatenated into logical lines that the compiler will see by using \ followed by a newline:

Each instance of a backslash character () immediately followed by a new-line character is deleted, splicing physical source lines to form logical source lines. Only the last backslash on any physical source line shall be eligible for being part of such a splice.

This can be easily checked in the preprocessor output: create file.cpp with

pri\
ntf ("Hell\
o world"\
);

then

cpp file.cpp

gives

printf ("Hello world");

or

printf 
    ("Hello world");

which is what the compiler sees (checked on Ubuntu; your mileage can vary).

Now, applying this rule to a multiline macro,

#define SOME_BIG_MACRO(input)\
  SOME_FUNCTION_CALL() \
  SOME_OTHER_FUNCTION_CALL()

is understood by the preprocessor as

#define SOME_BIG_MACRO(input)   SOME_FUNCTION_CALL()   SOME_OTHER_FUNCTION_CALL()

because all \ and the next newline are ignored.

Similarly,

#define SOME_BIG_MACRO(input)\
  SOME_FUNCTION_CALL()  /* this does... */ \
  SOME_OTHER_FUNCTION_CALL()

is seen by the preprocessor as

#define SOME_BIG_MACRO(input)   SOME_FUNCTION_CALL()  /* this does... */   SOME_OTHER_FUNCTION_CALL()

However,

#define SOME_BIG_MACRO(input)\
  SOME_FUNCTION_CALL()  \ // this does...
  SOME_OTHER_FUNCTION_CALL()

becomes two lines:

#define SOME_BIG_MACRO(input)   SOME_FUNCTION_CALL()  \ // this does...
  SOME_OTHER_FUNCTION_CALL()

because the second \ is not followed by newline and thus is preserved, as well as a newline not preceeded by a \. This causes compile error.

While

#define SOME_BIG_MACRO(input)\
  SOME_FUNCTION_CALL()  // this does... \
  SOME_OTHER_FUNCTION_CALL()

becomes one line:

#define SOME_BIG_MACRO(input)  SOME_FUNCTION_CALL()  // this does...   SOME_OTHER_FUNCTION_CALL()

which is syntactically correct but the macro is incomplete. Some compilers report this as an error, because most probably this is not the intention of the programmer. Others, such as Ubuntu cc, silently apply the rules defined by the standard.

Since a macro can occupy only one logical line (though several physical lines, using the newline escaping mechanism), any // comment on this line causes all the rest of the macro to be ignored.

Conclusion: a // comment can only occur at the end of a (multi- or single-line) macro, while /* comment */ can perfectly be used inside the macro.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)