Use of two variables in a for loop

Jun 26, 2013 at 1:18am
Here's the first part of some generic for loop:

 
for (int n=0; n<10; n++)


I'm wondering if it is okay to add two tracking variables (if there's a special term, I don't know it, sorry), maybe like so:

 
for (int n=0 , int e=0; n<10, e>0; n++, e--)
Jun 26, 2013 at 1:31am
If it did exist, would it be doing the loop until one of the statements become untrue, or both?
Last edited on Jun 26, 2013 at 1:31am
Jun 26, 2013 at 1:32am
That's why I'm asking...
Jun 26, 2013 at 1:38am
It is possible if the two declared variables are of the same type. Remember that you can only have two semi-colons in a for statement.
 
for(int I(0), j(10); I < 10 || j > 0; ++I, --j)

Note that I use OR and not a comma operator in the condition.

If the types are different, like if you are using STL iterators, you can always declare them beforehand. What variables are checked and what variable is "incremented" is not restricted to the declared variable inside.
1
2
3
4
5
std::list<int> contain1(4,5);
std::vector<int> contain2(10,10);
auto iter1(contain1.begin());
auto iter2(contain2.begin());
for(; iter1 != contain1.end() && iter2 != contain2.end(); ++iter1, ++iter2) 
Jun 26, 2013 at 1:39am
closed account (Dy7SLyTq)
i believe all of that is correct, except for the n<10, e>0. you want to use the && operator like you would in a normal condition. i think you said you were writing python so its the c++ version of the and operator
Jun 26, 2013 at 1:45am
Oh okay, thanks, simple enough.
Topic archived. No new replies allowed.