define macro as linenumber

Viewed 112

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.

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);

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__;.

Related