Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why c++ does not support multiple initializers in for loop? [duplicate]

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?

like image 448
Jichao Avatar asked Jun 29 '12 03:06

Jichao


People also ask

Can you declare multiple variables in a for loop in C?

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.

Can you have multiple initialization statements in for loop?

No, you can only have one initializing statement.

Is initialization necessary in for loop?

You do not need it for an enhanced for loop.


1 Answers

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

like image 192
Nawaz Avatar answered Oct 22 '22 05:10

Nawaz