Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it legal to use the #line directive in a macro argument?

I noticed that this program compiles with gcc:

#define X(A) A

int x = X(
#line 3 "test1.c"
        0
        );

However, Visual Studio fails to compile it:

main.cpp
main.cpp(6): error C2121: '#': invalid character: possibly the result of a macro expansion
main.cpp(6): error C2065: 'line': undeclared identifier
main.cpp(6): error C2143: syntax error: missing ';' before 'constant'
main.cpp(6): error C2059: syntax error: 'constant'

I wonder: is the program even legal, or is it silently relying on undefined (or implementation defined) behaviour which happens to make gcc accept the code?

like image 901
Frerich Raabe Avatar asked Oct 22 '25 20:10

Frerich Raabe


1 Answers

It's invalid. The behaviour is undefined, so no diagnostic is required, and implementations are allowed to accept the code.

From the C standard, 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.

The C++ standard contains these exact same words in 16.3 Macro replacement.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!