如何编译器知道,在一个函数调用中的逗号不是逗号操作符? [英] How does the compiler know that the comma in a function call is not a comma operator?
问题描述
考虑函数调用(调用 INT总和(INT,INT)
)
printf("%d", sum(a,b));
编译器如何决定,,
在函数调用中使用 SUM(INT,INT)
不是逗号操作符?
How does the compiler decide that the ,
used in the function call sum(int, int)
is not a comma operator?
注意:我不想在函数调用实际上用逗号。我只是想知道编译器如何知道这是不是一个逗号操作符。
NOTE: I didn't want to actually use the comma operator in the function call. I just wanted to know how the compiler knows that it is not a comma operator.
推荐答案
看语法的C语言。它的上市,完全在标准的附录A 。它的工作方式是,你可以在C程序通过每个令牌退一步,在语法中的下一项匹配起来。在每一个步骤中,只有选项的数量有限,所以任何给定的字符的相互pretation将取决于上下文中出现的。在语法每个规则里面,每一行给出了程序匹配的有效替代品。
Look at the grammar for the C language. It's listed, in full, in Appendix A of the standard. The way it works is that you can step through each token in a C program and match them up with the next item in the grammar. At each step you have only a limited number of options, so the interpretation of any given character will depend on the context in which it appears. Inside each rule in the grammar, each line gives a valid alternative for the program to match.
特别是,如果你看看参数列表
,你会看到它包含一个明确的逗号。因此,每当编译器的C语言解析器中的参数列表的模式,逗号,它发现将被理解为参数分隔符,而不是逗号操作符。这同样适用于括号真(也可发生于前pressions)。
Specifically, if you look for parameter-list
, you will see that it contains an explicit comma. Therefore, whenever the compiler's C parser is in "parameter-list" mode, commas that it finds will be understood as parameter separators, not as comma operators. The same is true for brackets (that can also occur in expressions).
这工作,因为参数列表
规则是慎重使用分配-EX pression
规则,而不仅仅是纯前pression
规则。一个前pression
可以包含逗号,而一个分配-EX pression
不能。如果不是这样的语法是含糊不清,编译器会不知道该怎么办时,它遇到了一个参数列表里加上逗号。
This works because the parameter-list
rule is careful to use assignment-expression
rules, rather than just the plain expression
rule. An expression
can contain commas, whereas an assignment-expression
cannot. If this were not the case the grammar would be ambiguous, and the compiler would not know what to do when it encountered a comma inside a parameter list.
不过,左括号,例如,是的不的一个函数的定义/调用的一部分,或者如果
,,而
或为
语句,将PTED作为一名前pression的部分(除$ p $,因为没有其他选项,但只有一个前pression的开始是在这一点上一个有效的选择),然后在括号里面,前pression
语法规则将适用,并允许逗号运营
However, an opening bracket, for example, that is not part of a function definition/call, or an if
, while
, or for
statement, will be interpreted as part of an expression (because there's no other option, but only if the start of an expression is a valid choice at that point), and then, inside the brackets, the expression
syntax rules will apply, and that allows comma operators.
这篇关于如何编译器知道,在一个函数调用中的逗号不是逗号操作符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!