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).
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;
}
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With