分配期间如何逗号操作符的工作? [英] How does comma operator work during assignment?

查看:114
本文介绍了分配期间如何逗号操作符的工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  int类型的= 1;
INT B =(1,2,3);
COUT<< A + B<< ENDL; //这个打印4


  1. (1,2,3)某种在C结构++(一些原始类型的列表,也许?)

  2. 为什么 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

  1. Is (1,2,3) some sort of structure in c++ (some primitive type of list, maybe?)
  2. Why is b assigned the value 3? 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屋!

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