Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
185 views
in Technique[技术] by (71.8m points)

c++ - 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).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...