Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

define macro as linenumber

Is it possible to define a macro so it has the value of the line it is defined on?

I know about __LINE__ but it is expanding too late.

#define MYLINE __LINE__  // line 1
printf("%d\n", MYLINE);  // line 2
printf("%d\n", MYLINE);  // line 3

The above doesn't do what I want. I would want it to print 1 twice but it instead prints 2 and 3.

like image 759
GGG Avatar asked Mar 02 '23 16:03

GGG


2 Answers

A macro is like textual replacement (i.e. MYLINE is replaced with __LINE__ everywhere). You won't be able to do that.

You can use a constant, though:

const int line = __LINE__;
printf("line %d\n", line);
printf("line %d\n", line);
like image 156
S.S. Anne Avatar answered Mar 07 '23 16:03

S.S. Anne


No, because:

  • __LINE__ is a macro name. (C 2018 6.10.8 1)
  • “The preprocessing tokens within a preprocessing directive are not subject to macro expansion unless otherwise stated.” (C 2018 6.10 7)
  • The specification for # define directives does not state otherwise. (C 2018 6.10.3)

So macro replacement can occur only where a macro is used subsequently; it cannot occur in the # define directive itself.

You can define constants with the line number, such as static const int MyLine = __LINE__;.

like image 20
Eric Postpischil Avatar answered Mar 07 '23 16:03

Eric Postpischil