为什么c ++不支持for循环中的多个初始值设定项? [重复]

问题描述 投票:14回答:3

可能重复: In C++ why can't I write a for() loop like this: for( int i = 1, double i2 = 0; Why is it so 'hard' to write a for-loop in C++ with 2 loop variables?

#include <iostream>
using namespace std;

int main()
{
    for (int i = 0, double j = 3.0; i < 10; i++, j+=0.1)
        cout << i << j << endl;
    return 0;
}

不编译,因为for循环初始化程序块中有两个声明。

但为什么?

c++ for-loop programming-languages language-lawyer
3个回答
17
投票

在C ++语法中,不同的数据类型用;(如果不是函数)分隔。在for循环中,一旦找到;,意义就会改变。即

for (<initializations>; <condition>; <next operation>)

其他原因可能是为了避免已经复杂的语法的复杂性,不允许使用此功能。

如果要在for循环范围中声明变量,则可以始终模拟该情况:

int main()
{
  {
    double j = 3.0;
    for (int i = 0; i < 10; i++, j+=0.1)
        cout << i << j << endl;
  }
    return 0;
}

43
投票

如果你想要intdouble两者,在初始化中,那么一种方法是定义一个匿名结构!是的,您也可以在struct循环中定义for。它似乎是一个鲜为人知的C ++特性:

#include <iostream>

int main()
{
    for( struct {int i; double j;} v = {0, 3.0}; v.i < 10; v.i++, v.j+=0.1)
       std::cout << v.i << "," << v.j << std::endl; 
}

输出:

0,3
1,3.1
2,3.2
3,3.3
4,3.4
5,3.5
6,3.6
7,3.7
8,3.8
9,3.9

在线演示:http://ideone.com/6hvmq


10
投票

因为已经采用了语法。在变量声明/定义中,用逗号分隔会添加相同类型的新变量,而不是不同类型的变量。该语法在for循环中可用:

for ( std::vector<int>::const_iterator it = v.begin(), end = v.end();
      it != end; ++it ) {
   // do something here
}
© www.soinside.com 2019 - 2024. All rights reserved.