简体   繁体   English

在c中使用逗号运算符

[英]Using comma operator in c

I have read that comma operator is used to assign expression, and the right expression is supplied to lvalue.我读过逗号运算符用于分配表达式,并将正确的表达式提供给左值。

But why does this program assign left expression to lvalue when not using parenthesis?但是为什么这个程序在不使用括号时将左表达式分配给左值? I am using turbo c compiler.我正在使用 turbo c 编译器。

int b=2;
int a;
a=(b+2,b*5);  // prints 10 as expected
a=b+2,b*5;    // prints 4 when not using parenthesis

Also the following works:还有以下作品:

int a =(b+2,b*5);

But this generates an error:但这会产生错误:

int a =b+2,b*5;   // Error

I can't understand why.我不明白为什么。

Because precedence of , operator is lower than of = one, this...因为,运算符的优先级低于 of = 1,所以这...

a=b+2,b*5;

... will actually be evaluated as... ...实际上将被评估为...

a = b + 2;
b * 5;

With int i = b + 2, b * 5;int i = b + 2, b * 5; is a bit different, because comma has different meaning in declaration statements, separating different declarations from each other.有点不同,因为逗号在声明语句中具有不同的含义,将不同的声明相互分隔。 Consider this:考虑一下:

int a = 3, b = 4;

You still have comma here, but now it separates two variable assignment-on-declarations.您在这里仍然有逗号,但现在它分隔了两个变量赋值声明。 And that's how the compiler attempts to treat that line from your example - but fails to get any meaning from b * 5 line (it's neither assignment nor declaration).这就是编译器尝试从您的示例中处理该行的方式 - 但无法从b * 5行中获得任何含义(它既不是赋值也不是声明)。

Now, int a = (b + 2, b * 5) is different: you assign a value of b + 2, b * 5 expression to a variable a of type int .现在, int a = (b + 2, b * 5)有所不同:您b + 2, b * 5表达式的值分配给int类型的变量a The first sub-expression is discarded, leaving you just with b * 5 .第一个子表达式被丢弃,只剩下b * 5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM