运算符中的c ++空间,规则是什么 [英] c++ spaces in operators , what are the rules

查看:122
本文介绍了运算符中的c ++空间,规则是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这些表达式中的空格是否具有任何含义:
假设:

Does spaces have any meaning in these expressions:
assume:

int a = 1;  
int b = 2;  

1)

int c = a++ +b;

或者,
2)

int c = a+ ++b;

当我在Visual Studio中运行这两个时,会得到不同的结果.这是正确的行为吗?规范说明了什么?
通常,应该先评估什么,然后是增量还是增量?

When I run these two in visual studio, I get different results. Is that the correct behavior, and what does the spec says?
In general, what should be evaluated first, post-increment or pre-increment?

我应该这样说
c =a+++b;
无法在Visual Studio上编译.但我认为应该.似乎首先评估了postfix ++.

I should say that
c =a+++b;
Does not compile on visual studio. But I think it should. The postfix++ seems to be evaluated first.

推荐答案

也许有助于理解程序解析的一般体系结构.

Maybe it helps to understand the general architecture of how programs are parsed.

简而言之,解析程序(C ++或其他)分为两个阶段:词法分析器和解析器.

In a nutshell, there are two stages to parsing a program (C++ or others): lexer and parser.

词法分析器获取文本输入并将其映射到一系列符号.这是处理空格的时候,因为它们告诉符号在哪里.空格在某些地方确实很重要(例如,在intc之间,以免与符号intc混淆),而在其他地方则无关紧要(例如,在a++之间,因为没有歧义将它们分开).

The lexer takes the text input and maps it to a sequence of symbols. This is when spaces are handled because they tell where the symbols are. Spaces really matter at some places (like between int and c, to not confuse with the symbol intc) but not others (like between a and ++ because there is no ambiguity to separate them).

第一个示例:

int c = a++ +b;

给出以下符号,每个符号都在其自己的行上(实现可能会以稍微不同的方式实现):

gives the following symbols, each on its own row (implementations may do this in slightly different ways of course):

int
c
=
a
++
+
b
;

在另一种情况下:

int c = a+ ++b;

符号改为:

int
c
=
a
+
++
b
;

解析器然后根据符号并根据某种语法构建一棵树(抽象语法树,AST).特别地,根据C ++语法,+作为附加项的优先级比一元++运算符的优先级低(无论后缀或前缀如何).这意味着第一个示例在语义上与(a++) + b相同,而第二个示例与a+ (++b)类似.

The parser then builds a tree (Abstract Syntax Tree, AST) out of the symbols and according to some grammar. In particular, according to the C++ grammar, + as an addition has a lower precedence than the unary ++ operator (regardless of postfix or prefix). This means that the first example is semantically the same as (a++) + b while the second is like a+ (++b).

在您的示例中,AST会有所不同,因为空格已在词法分析器阶段导致了不同的输出.

For your examples, the ASTs will be different, because the spaces already lead to a different output at the lexer phase.

请注意,+++之间不需要空格,因此a+++b

Note that spaces are not required between ++ and +, so a+++b would theoretically be fine, but this is not recommended for readability. So, some spaces are important for technical reasons while others are important for us users to read the code.

这篇关于运算符中的c ++空间,规则是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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