简体   繁体   English

取代__LINE__巨集

[英]Replacing __LINE__ macro

I read about macros using Cppreference . 我阅读了有关使用Cppreference的宏的信息

__LINE__ : expands to the source file line number, an integer constant, can be changed by the #line directive __LINE__ :扩展为源文件的行号,一个整数常量,可以通过#line指令进行更改

I made c++ program to test __LINE__ macro. 我制作了c ++程序来测试__LINE__宏。

#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 ? 为什么上面的代码输出为20 Why does not 10? 为什么不10?

If you want to print 10 then change L into something that is not a macro: 如果要打印10则将L更改为不是宏的内容:

constexpr int L = __LINE__;

Otherwise the macro L would be substituted on the line int i = L; 否则,将在行int i = L;替换 L and become: 并成为:

int i = __LINE__;

Where it will have to be substituted again for the line number, and read the last #line directive. 在该位置必须再次替换行号,并阅读最后的#line指令。

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. 当您#define L __LINE__它仅指定当L出现在源代码中时应替换L 标记 It does not substitute anything at the point of L 's own definition. L自己的定义上,它不能替代任何东西。

C++ - [cpp.replace]/9 or C - [6.10.3 Macro replacement]/9 C ++-[cpp.replace] / 9C-[6.10.3宏替换] / 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. 然后重新扫描替换列表以获取更多的宏名称,如下所示。

  #define y 42
  #define x y

This makes x defined as a sequence of preprocessing tokens that contains one token y . 这将x定义为包含一个标记y的一系列预处理标记。 Not the token 42 . 不是令牌42

  cout << x;

This will expad x to y and then y to 42 . 这会将x扩展为y然后将 y扩展为42

#undef y
#define y "oops"

x is still defined as y . x仍定义为y

cout << x;

You guess what happens. 你猜会发生什么。 __LINE__ isn't special in this regard. __LINE__在这方面并不特殊。

Your #line preprocessor directive changes the value to 20 : 您的#line预处理程序指令将值更改为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 . 在将值更改为20的预处理指令之后,在main()函数中的使用位置(未定义位置)处扩展该宏。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM