逗号作为分隔符和运算符 [英] Comma as a separator and operator
问题描述
所以我在某个地方遇到了这个问题:
So I came across this question somewhere:
情况1:
int a;
a = 1, 2, 3;
printf("%d", a);
情况2:
int a = 1, 2, 3;
printf("%d", a);
解释说:
第二种情况下会出错,因为使用逗号作为分隔符;在第一种情况下, =
优先于,
,因此基本上是(a = 1),2、3
;
The second case gives error because comma is used as a separator, In first case =
takes precedence over ,
so it is basically (a=1), 2, 3
;
但是我想问为什么案例2中的 =
不优先于,
?
But I want to ask why does =
not take precedence over ,
in Case 2?
推荐答案
此
int a = 1, 2, 3;/* not a valid one */
是错误的,因为因为 =
具有更高的优先级,所以它在内部变为 int a = 1
,并且没有 2
和 3
,这就是为什么该语句无效并导致编译时错误的原因.
is wrong because since =
has higher priority, so it become int a = 1
internally and there is no name for 2
and 3
thats why this statement is not valid and cause compile time error.
为避免这种情况,您可能要使用
To avoid this you might want to use
int a = (1, 2, 3); /* evaluate all expression inside () from L->R and assign right most expression to a i.e a=3*/
还有这里
int a;
a = 1,2,3;
有两个运算符 =
和
,请参阅 man运算符
.赋值运算符 =
的优先级高于逗号
运算符.因此它变为 a = 1
.
there are two operator =
and ,
and see man operator
. The assignment operator =
has higher priority than comma
operator. So it becomes a=1
.
a = 1,2,3;
| L--->R(coma operator associativity)
this got assigned to a
例如
int x = 10, y = 20,z;
z = 100,200,y=30,0; /* solve all expression form L to R, but finally it becomes z=100*/
printf("x = %d y = %d z = %d\n",x,y,z);/* x = 10, y = 30(not 20) z = 100 */
z = (100,200,y=30,0); /* solve all expression form L to R, but assign right most expression value to z*/
这篇关于逗号作为分隔符和运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!