编译器如何知道函数调用中的逗号不是逗号运算符? [英] How does the compiler know that the comma in a function call is not a comma operator?

查看:14
本文介绍了编译器如何知道函数调用中的逗号不是逗号运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑函数调用(调用int sum(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 程序中的每个标记,并将它们与语法中的下一项匹配.在每个步骤中,您只有有限数量的选项,因此任何给定字符的解释将取决于 它出现的上下文.在语法中的每条规则中,每一行都为程序提供了一个有效的替代方案来匹配.

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.

具体来说,如果您查找 parameter-list,您会看到它包含一个显式逗号.因此,每当编译器的 C 解析器处于参数列表"模式时,它找到的逗号将被理解为 参数分隔符,而不是 逗号运算符.括号也是如此(也可以出现在表达式中).

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).

这是因为 parameter-list 规则谨慎使用 assignment-expression 规则,而不仅仅是普通的 expression 规则.expression 可以包含逗号,而 assignment-expression 不能.如果不是这种情况,语法就会不明确,编译器在遇到参数列表中的逗号时将不知道该怎么做.

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.

然而,一个左括号,例如,它不是函数定义/调用的部分,或者一个ifwhile,或 for 语句,将被解释为表达式的一部分(因为没有其他选项,但前提是表达式的开头是该点的有效选择),然后,在括号内,expression 语法规则将适用,并且允许逗号运算符.

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屋!

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