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.
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)# 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__;
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With