逗号运算符的局限性
我已阅读这个问题,我想补充一点,可以做什么不能使用逗号运算符来完成。这让我很困惑,因为我可以这样做:
int arr[3];
arr[0]=1,arr[1]=2,arr[2]=3;
但是当我这样做时:
int arr[3],arr[0]=1,arr[1]=2,arr[2]=3;
它给了我一个编译器错误。
我想问一下,逗号运算符在实际应用中有何局限性?
I have read this question and I want to add to it that what are the things that can not be done using the comma operator. This has confused me a lot, as I can do this:
int arr[3];
arr[0]=1,arr[1]=2,arr[2]=3;
But when I do:
int arr[3],arr[0]=1,arr[1]=2,arr[2]=3;
It gives me a compiler error.
I want to ask that what are the limitations of the comma operator in real practice?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
需要认识到的一件事是,并非 C 中逗号的所有使用都是逗号运算符的实例。将第二个示例更改为语法声明:
逗号不是运算符,它们只是分隔列表中声明符实例所需的语法。
此外,参数/参数列表中使用的逗号不是逗号运算符。
在我看来,使用逗号运算符几乎总是一个坏主意 - 它只会导致不必要的混乱。在大多数情况下,使用逗号运算符所做的事情可以使用单独的语句更清楚地完成。
很容易想到的两个例外是 for 语句的控制子句内部,以及绝对需要将多个“事物”塞入单个表达式中的宏,即使这样也应该这样做当没有其他合理选择时)。
One thing to realize is that not all uses of a comma in C are instances of the comma operator. Changing your second example to be a syntactically declaration:
the commas are not operators, they're just syntax required to separate instances of declarators in a list.
Also, the comma used in parameter/argument lists is not the comma operator.
In my opinion the use of the comma operator is almost always a bad idea - it just causes needless confusion. In most cases, what's done using a comma operator can be more clearly done using separate statements.
Two exceptions that come to mind easily are inside the control clauses of a
for
statement, and in macros that absolutely need to cram more than one 'thing' into a single expression, and even this should only be done when there's no other reasonable option).您可以在表达式可以出现的大多数地方使用逗号运算符。但也有一些例外;值得注意的是,不能在常量表达式中使用逗号运算符。
使用逗号运算符时还必须小心,其中逗号也用作分隔符,例如,在调用函数时,必须使用括号对逗号表达式进行分组:
您的示例是声明:
在声明中,您可以声明通过用逗号分隔多个内容,因此这里也使用逗号作为分隔符。另外,您不能像这样将表达式添加到声明的末尾。 (请注意,您可以使用
int arr[3] = { 1, 2, 3 };
获得所需的结果)。You can use the comma operator most anywhere that an expression can appear. There are a few exceptions; notably, you cannot use the comma operator in a constant expression.
You also have to be careful when using the comma operator where the comma is also used as a separator, for example, when calling functions you must use parentheses to group the comma expression:
Your example is a declaration:
In a declaration, you can declare multiple things by separating them with the comma, so here too the comma is used as a separator. Also, you can't just tack on an expression to the end of a declaration like this. (Note that you can get the desired result by using
int arr[3] = { 1, 2, 3 };
).