我经常发现 C 和 C++ 标准难以阅读和理解,即使是简单的英文句子及其措辞也给人糟糕的体验。最重要的是,语言语法完全是 hell 。我相信很多人都有同样的感受,至少我的 friend 们是这样。
我想通过一些例子来理解它。让我们从这个开始(它试图解释为什么 C++ 中的条件表达式
与 C 中的条件表达式
不同:(引自 wikipedia)
The binding of operators in C and C++ is specified (in the corresponding Standards) by a factored language grammar, rather than a precedence table. This creates some subtle conflicts. For example, in C, the syntax for a conditional expression is:
logical-OR-expression ? expression : conditional-expression
while in C++ it is:
logical-OR-expression ? expression : assignment-expression
Hence, the expression:
e = a < d ? a++ : a = d
is parsed differently in the two languages. In C, this expression is a syntax error, but many compilers parse it as:
e = ((a < d ? a++ : a) = d)
which is a semantic error, since the result of the conditional-expression (which might be a++) is not an lvalue. In C++, it is parsed as:
e = (a < d ? a++ : (a = d))
which is a valid expression.
请人解释一下上述引文中的粗体字!请用更多的例子来解释语法(尤其是那些 C 和 C++ 不同的例子)。
编辑:我只想知道如何阅读和理解它们。我的意思是,如果我用口语来解释,那我该怎么做呢?
最佳答案
这里是 C++ grammar for expressions 的描述,它将赋值表达式定义为
assignment-expression:
conditional-expression
unary-expression assignment-operator assignment-expression
在简单的英语中,赋值表达式可以是条件表达式或一元表达式,后跟赋值运算符,然后是赋值表达式。因此,您的下一个问题是“什么是条件表达式”,您引用了语法的那一部分,并继续前进,直到到达底部!
所以在 C++ 中,您可以看到您提到的运算符可以像在 C 中一样采用“条件表达式”,但也可以是赋值
因此,戴上“C”帽子,您将运算符的最后 a = d
部分视为赋值,这是 C 语法不应该允许的。相反,似乎一些编译器将运算符的最后部分简单地解析为 a
以给出
e = (a < d ? a++ : a) = d
但在 C++ 中,在那里找到一个赋值是有效的,所以 a = d
被完全接受为最终表达式,所以你得到
e = (a < d ? a++ : (a = d))
关于c++ - 如何阅读和理解 C & C++ 标准以及其中使用的语言语法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4352623/