11

Is it possible to do multiple operations in increment part of for loop in C/C++? Something like this:

int a = 0, b = 0, c = 5;
for(; a < c; increase a by 1 and increase b by 2)
4

2 回答 2

23

使用逗号运算符:

for (; a < c; ++a, b += 2)
于 2013-10-07T23:41:27.497 回答
9

对的,这是可能的。您还可以在循环内声明多个变量,并且之前不需要这样做。

for (int a = 0, b = 0, c = 5; a < c; ++a, b += 2)
于 2013-10-07T23:47:30.147 回答