简体   繁体   English

C++ 用于使用逗号运算符的多个控制语句

[英]C++ for with multiple control statements using comma operator

How does comma operator if it is used in a 'for loop' for writing multiple control statements?如果在“for循环”中使用逗号运算符来编写多个控制语句,它如何? i tried我试过了

#include <iostream>

using namespace std;

int main() {
        for (int x = 0, y = 0; x < 3, y < 4; ++x, ++y) {
                cout << x << " " << y << endl;
        }
        return 0;
}

and it seems like only the last expression is evaluated.似乎只评估了最后一个表达式。 Ty

This is how comma operator works.这就是逗号运算符的工作方式。 Its 1st operand x < 3 is evaluated, then the result is discarded;它的第一个操作数x < 3被评估,然后结果被丢弃; then the 2nd operand y < 4 is evaluated and the value is returned as the return value of the comma operator.然后计算第二个操作数y < 4并将该值作为逗号运算符的返回值返回。 x < 3 has not any effects here. x < 3在这里没有任何影响。

You might want to use operator&& or operator||您可能想使用operator&&operator|| for this case, eg x < 3 && y < 4 or x < 3 || y < 4对于这种情况,例如x < 3 && y < 4x < 3 || y < 4 x < 3 || y < 4 based on your intent. x < 3 || y < 4根据您的意图。

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

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