分配期间如何逗号操作符的工作? [英] How does comma operator work during assignment?
问题描述
int类型的= 1;
INT B =(1,2,3);
COUT<< A + B<< ENDL; //这个打印4
- 是
(1,2,3)
某种在C结构++(一些原始类型的列表,也许?) - 为什么
B
分配值3
?该编译器简单地从列表中取最后价值?
是的,这正是它:编译器会的最后一个值。这是逗号运算符,并评估其运算由左到右,并返回最右边之一。它还决心左到右。为什么有人会写code这样的,我不知道:)
所以 INT B =(1,2,3)
等同于 INT B = 3
。这不是任何一种原始的列表,逗号操作符,
主要用于在一个前pression的背景下,像<$ C $,以评估多个命令C> A + = 5,b + = 4,C + = 3,D + = 2,E + = 1,F 例如
int a = 1;
int b = (1,2,3);
cout << a+b << endl; // this prints 4
- Is
(1,2,3)
some sort of structure in c++ (some primitive type of list, maybe?) - Why is
b
assigned the value3
? Does the compiler simply take the last value from the list?
Yes, that's exactly it: the compiler takes the last value. That's the comma operator, and it evaluates its operands left-to-right and returns the rightmost one. It also resolves left-to-right. Why anyone would write code like that, I have no idea :)
So int b = (1, 2, 3)
is equivalent to int b = 3
. It's not a primitive list of any kind, and the comma operator ,
is mostly used to evaluate multiple commands in the context of one expression, like a += 5, b += 4, c += 3, d += 2, e += 1, f
for example.
这篇关于分配期间如何逗号操作符的工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!