什么是术语“词汇”在C ++中的意思? [英] What does the term "lexical" means in C++?

查看:104
本文介绍了什么是术语“词汇”在C ++中的意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读到有词法常量,词法运算符,词法作用域等。对于任何运算符或某个标识符的范围,术语词法如何改变常量的含义,例如字符串字面量。

I read there are lexical constants, lexical operators, lexical scope etc. how does the term "lexical" changes the meaning for a constant e.g string literal, for any operator, or a scope of some identifier ?

推荐答案

lexical表示它与源代码相关。

"lexical" means that it is related to the source code.

1 是一个词法常量。 OTOH, sizeof(char)也是一个编译时积分常量表达式,但它不是一个词法常量。在词法上,它是 sizeof 运算符的调用。

For example, 1 is a lexical constant. OTOH, sizeof(char) is also a compile-time integral constant expression, but it is not a lexical constant. Lexically, it is an invocation of the sizeof operator.

词法运算符用于源代码。

Lexical operators work on the source code. The preprocessor operators fall into this category.

在大多数情况下,无论我使用 1 还是 sizeof(char)在我的程序的任何地方。但是,由于词法运算符 ## 的参数有很大的区别,因为这些工作在实际代码而不是评估结果:

In most cases, it makes no difference whether I use 1 or sizeof(char) anywhere in my program. But, as the argument of the lexical operators # or ## it makes a considerable difference, because these work on the actual code and not the result of evaluation:

#define STR(x) #x

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

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

Finally, lexical scope means the portion of the program source code where are identifier exists (is recognized, can be used). This is in contrast to the dynamic scope, also known as object lifetime, which is the portion of the program where the object exists (maintains its value and may be manipulated indirectly via pointer or reference, even though the name is not in lexical scope).

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 ++中的意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆