gpt4 book ai didi

c++ - 替换 __LINE__ 宏

转载 作者:太空宇宙 更新时间:2023-11-04 05:02:03 24 4
gpt4 key购买 nike

我阅读了有关使用 Cppreference 的宏的信息.

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

我制作了 c++ 程序来测试 __LINE__ 宏。

#include <iostream>
using namespace std;

#line 10
#define L __LINE__

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

输出:

20

为什么上面代码的输出是20?为什么不是 10?

最佳答案

如果你想打印 10 然后把 L 改成不是宏的东西:

constexpr int L = __LINE__;

否则, L 将被替换为 int i = L; 行并变为:

int i = __LINE__;

必须再次替换行号的位置,并阅读最后的 #line 指令。

回想一下,宏执行标记替换。当您 #define L __LINE__ 时,它仅指定 L 出现在源代码中时应替换哪些标记。它不会替换 L 自己定义的任何内容。

C++ - [cpp.replace]/9C - [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.

关于c++ - 替换 __LINE__ 宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47549362/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com