gpt4 book ai didi

c++ - 术语 "lexical"在 C++ 中意味着什么?

转载 作者:可可西里 更新时间:2023-11-01 17:52:26 27 4
gpt4 key购买 nike

我读到有词法常量、词法运算符、词法范围等。术语“词法”如何改变常量(例如字符串文字)、任何运算符或某些标识符的范围的含义?

最佳答案

“词法”是指与源代码相关。

例如,1 是一个词法常量。 OTOH,sizeof(char) 也是编译时整数常量表达式,但它不是词法常量。从词法上讲,它是 sizeof 运算符的调用。

词法运算符作用于源代码。预处理器运算符属于这一类。

在大多数情况下,我在程序中的任何地方使用 1 还是 sizeof(char) 都没有区别。但是,作为词法运算符 ### 的参数,它产生了相当大的差异,因为它们作用于实际代码而不是计算结果:

#define STR(x) #x

std::string one = STR(1);
std::string also_one = STR(sizeof(char));

最后,词法范围是指程序源代码中存在标识符的部分(被识别,可以使用)。这与动态范围相反,也称为对象生命周期,它是对象存在的程序部分(保持其值并且可以通过指针或引用间接操作,即使名称不在词法范围内) .

string f(string x) { return "2" + x; } // main's "y" is not in lexical scope, however it is in dynamic scope, and will not be destroyed yet

int main(void)
{
string y = "5.2"; // y enters lexical scope and dynamic scope

string z = f("y"); // y leaves lexical scope as f is called, and comes back into lexical scope when f returns

return z.size();
// z leaves lexical and dynamic scope, destructor is called
}

关于c++ - 术语 "lexical"在 C++ 中意味着什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8042819/

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