msc
msc

Reputation: 34568

Replacing __LINE__ macro

I read about macros using Cppreference.

__LINE__ : expands to the source file line number, an integer constant, can be changed by the #line directive

I made c++ program to test __LINE__ macro.

#include <iostream>
using namespace std;

#line 10
#define L __LINE__

int main() 
{
    #line 20
    int i = L;
    cout<<i<<endl;
    return 0;
}

Output :

20

Why output of the above code is 20? Why does not 10?

Upvotes: 0

Views: 1346

Answers (3)

If you want to print 10 then change L into something that is not a macro:

constexpr int L = __LINE__;

Otherwise the macro L would be substituted on the line int i = L; and become:

int i = __LINE__;

Where it will have to be substituted again for the line number, and read the last #line directive.

Recall that macros perform token substitution. When you #define L __LINE__ it only specifies what tokens should L be substituted for when it appears in the source. It does not substitute anything at the point of L's own definition.

C++ - [cpp.replace]/9 or C - [6.10.3 Macro replacement]/9

A preprocessing directive of the form

# define identifier replacement-list new-line

defines an object-like macro that causes each subsequent instance of the macro name to be replaced by the replacement list of preprocessing tokens that constitute the remainder of the directive. The replacement list is then rescanned for more macro names as specified below.

Upvotes: 9

Ron
Ron

Reputation: 15491

Your #line preprocessor directive changes the value to 20:

#line 20

The macro is expanded where used (not where defined) which is in your main() function, after the preprocessor directive which changes the value to 20.

Upvotes: 3

n. m. could be an AI
n. m. could be an AI

Reputation: 119847

  #define y 42
  #define x y

This makes x defined as a sequence of preprocessing tokens that contains one token y. Not the token 42.

  cout << x;

This will expad x to y and then y to 42.

#undef y
#define y "oops"

x is still defined as y.

cout << x;

You guess what happens. __LINE__ isn't special in this regard.

Upvotes: 5

Related Questions