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 << e
If you're having trouble with macros, there's a standard do..while
trick that works perfectly:
#define MYFOR(init, test, post, body) \
do \
{ \
init \
for( ; test; post) \
body \
} while(0)
Use it as follows:
MYFOR( int i = 0; float j = 0.0f; , i < 10 , (i += 1, j = 2.0f * i),
{
cout << j << endl;
} );
It's ugly, but it does what you want: the scope of i
and j
is limited by the do..while
loop from the macro, and it requires a semicolon at the end, so you won't get bitten by putting it in the predicate of an if/else statement.