Multiple Counter Problem In For Loop

后端 未结 7 1129
余生分开走
余生分开走 2020-12-16 10:59

Why is this not valid

for( int i = 0, int x = 0; some condition; ++i, ++x )

and this is

int i, x;
for( i = 0, x = 0; some c         


        
7条回答
  •  抹茶落季
    2020-12-16 11:50

    Why should it be valid? It is a syntactically meaningless construst. What were you trying to say with it?

    The first part of for header is a declaration. The

    int i = 0, int x = 0
    

    is not a valid declaration. It will not compile in for for the same reason why it won't compile anywhere else in the program

    int i = 0, int x = 0; // Syntax error
    

    When you need to declare two objects of type int in one declaration, you do it as follows

    int i = 0, x = 0; // OK
    

    The same thing can be used in for

    for( int i = 0, x = 0; some condition; ++i, ++x )  
    

    (But when you need to declare two variables of different types, it can't be done by one declaration and, therefore, both cannot be declared in for at the same time. At least one of them will have to be declared before for.)

提交回复
热议问题