简体   繁体   中英

If an outer for loop has no braces, will an inner for loop be considered as a single statement?

I know that if no curly braces are used for a for loop then there can be only a single statement following it. My question is in this code:

for(int i=0;i<=10;i++)
  for(int j=10;j>=1;j--){
    if(i!=j)
      break;
    n=n+1;
  }
System.out.println(n);

Does the first loop consider the entire second for loop

for(int j=10;j>=1;j--){
  if(i!=j)
    break;
  n=n+1;
}

as a single statement ? I know it is good coding convention to use braces but I just want to know what happens here.

A for statement can be followed immediately by another for statement without the need for braces. If you are ever in doubt about this sort of info, check the language specification:

14.14.1 The basic for Statement describes the basic for statement as:

BasicForStatement:
  for ( [ForInit] ; [Expression] ; [ForUpdate] ) Statement

If you click the link for Statement you see all the valid options for what can follow:

Statement:
  StatementWithoutTrailingSubstatement
  LabeledStatement
  IfThenStatement
  IfThenElseStatement
  WhileStatement
  ForStatement

Notice the ForStatement in the line above.

Yes, the first (outer) loop will consider the entire 2nd (inner) loop.

Consider the following example:

for(int x=0; x<5; x++)     //Will only consider the next statement (enter y-loop)
    for(int y=0; y<5; x++) //Will only consider the next statement (enter z-loop)
        for(int z=0; z<5; x++) //Will only consider the next statement (enter if-statement)
            if(...)

The above statements work because even though each loop (without curly braces) will only loop the next statement, but in this case, the next statement is another loop statement.

The same applies to if-statements .

Consider this example 1:

if(a==0)
    if(b==0)
        System.out.println("This comes from b");
    else
        System.out.println("This else comes from b");

In the above code snippet, the else belong to the inner if-statement because the outer if only consider the next statement.

Consider this example 2:

if(a==0){
    if(b==0)
        System.out.println("This comes from b");
}    
else
    System.out.println("This else comes from b");

In the 2nd example, the else now belongs to the first if-statement .

Personally, I prefer to use braces to ensure clarity, however sometimes I still omit them when I am very sure what I am doing and when I know exactly what are the effects of omitting the braces.

does the first loop consider the entire second for loop -是的,是的,这是一个很好的约定,因为在非统一的编码环境中,省略括号比两个省略的字符要昂贵得多。

绝对可以,第二个for循环将被视为第一个循环的单个语句,该循环代表内部循环。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM