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?
Yes, I can declare multiple variables in a for-loop. And you, too, can now declare multiple variables, in a for-loop, as follows: Just separate the multiple variables in the initialization statement with commas.
No, you can only have one initializing statement.
You do not need it for an enhanced for loop.
If you want int
and double
both, in the initialization, then one way to do this is to define an anonymous struct! Yes, you can define struct
in the for
loop, as well. It seems to be a less known feature of 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;
}
Output:
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
Online demo : http://ideone.com/6hvmq
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With