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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…