为什么c ++不支持在for循环中的多个初始化器? [英] Why c++ does not support multiple initializers in for loop?

查看:143
本文介绍了为什么c ++不支持在for循环中的多个初始化器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:



为什么在C ++中用2个循环变量写一个for循环很困难?






  #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;
}


$ b



但是为什么?

(如果不是函数) 。在中为循环,一旦找到; ,含义就会改变。

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

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



如果您要在中为循环范围声明变量,那么您总是可以模拟这种情况:

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


Possible Duplicate:
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;
}

does not compile, becuase there are two declaration in the for-loop initializer block.

But Why?

解决方案

In C++ grammar, different data types are separated with ; (if not function). In for loop, once the ; is found the meaning is changed. i.e.

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

Other reason is possibly to avoid complexity in an already complex grammar, this feature is not allowed.

If you want to declare variables in for loop scope, then you can always simulate that situation:

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

这篇关于为什么c ++不支持在for循环中的多个初始化器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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