Assigning iterator and integer in same statement

Why can't you declare and assign an integer with an iterator using the comma operator?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
  #include <vector>
#include <iostream>

using namespace std;

class foo{
public:
	vector<int> m_bar;
	
};



int main(){

	foo a;
	a.m_bar.resize(10);

	//this is fine with the comma operator
	for (char a = 'c', int i = 0; i < 5; i++, a++)
		;

	// yet this is not fine with comma operator

	for (int i = 0, vector<int>::iterator iter = a.m_bar.begin();
		iter != a.m_bar.end(); iter++, i++)
		;

	return 0;
}


But this will work:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <vector>
#include <iostream>

using namespace std;

class foo{
public:
	vector<int> m_bar;
	
};



int main(){

	foo a;
	a.m_bar.resize(10);

	//this is fine with the comma operator
	for (char a = 'c', int i = 0; i < 5; i++, a++)
		;


	int i = 0;
	for (vector<int>::iterator iter = a.m_bar.begin();
		iter != a.m_bar.end(); iter++, i++)
		;

	return 0;
}
Last edited on
I would look elsewhere in your code, because I cannot compile this segment of code:
 
for (char a = 'c', int i = 0; i < 5; i++, a++);


The first part of the loop is throwing errors, because it evaluates to something like this.
 
char a = 'c', int i = 0;


The problem is that you can only declare/initialize two variables of the same type on one line:
 
int a = 0, i = 32;


Thus, you can only declare/initialize e both the char and the int like:
1
2
char a = 'c';
int i = 32;


I imagine that the same goes for the iterator.
Last edited on
You're right. You can only declare one variable in the for statement, although you can assign multiple.
Topic archived. No new replies allowed.