Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to define variables of two different types in a for loop initializer?

You can define 2 variables of the same type in a for loop:

int main() {
  for (int i = 0, j = 0; i < 10; i += 1, j = 2*i) {
    cout << j << endl;
  }
}

But it is illegal to define variables of different types:

int main() {
  for (int i = 0, float j = 0.0; i < 10; i += 1, j = 2*i) {
    cout << j << endl;
  }
}

Is there a way to do this? (I don't need to use i inside the loop, just j.)

If you have totally hacked and obscure solution, It's OK for me.

In this contrived example I know you could just use double for both variables. I'm looking for a general answer.

Please do not suggest to move any of the variables outside of for body, probably not usable for me as one is an iterator that has to disappear just after the loop and the for statement is to be enclosed in my foreach macro:

#define foreach(var, iter, instr) {                  \
    typeof(iter) var##IT = iter;                     \
    typeof(iter)::Element var = *var##IT;            \
    for (; var##_iterIT.is_still_ok(); ++var##IT, var = *var#IT) {  \
      instr;                                         \
    }                                                \
  }

It can be used thus:

foreach(ii, collection, {
  cout << ii;
}). 

But I need something that will be used like that:

foreach(ii, collection)
  cout << ii;

Please do not introduce any runtime overhead (but it might be slow to compile).

like image 766
Łukasz Lew Avatar asked May 14 '09 21:05

Łukasz Lew


2 Answers

Please do not suggest to move any of the variables outside of for body, probably not usable for me as the iterator has to disappear just after the loop.

You could do this:

#include <iostream>

int main( int, char *[] ) {
    {
        float j = 0.0;

        for ( int i = 0; i < 10; i += 1, j = 2*i ) {
            std::cout << j << std::endl;
        }
    }

    float j = 2.0; // works

    std::cout << j << std::endl;

    return 0;
}
like image 69
xian Avatar answered Oct 11 '22 02:10

xian


Well, it's ugly. But you could use pair.

int main() {
  for (std::pair<int,float> p(0,0.0f); 
       p.first < 10; 
       p.first += 1, p.second = 2*p.first) {
    cout << p.second << endl;
  }
}
like image 39
Mike G. Avatar answered Oct 11 '22 01:10

Mike G.