[英]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] / 9或C-[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__
在这方面并不特殊。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.