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

后端 未结 13 707
余生分开走
余生分开走 2020-12-19 06:12

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         


        
13条回答
  •  南方客
    南方客 (楼主)
    2020-12-19 06:53

    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.

提交回复
热议问题