检查 for 语句中的条件

Check condition in a for statement

我写了一个函数来检查区间内是否存在一个数字。 停止搜索的最佳方法是什么?这个:

for (i = a; i <= b; i++) {
  fi = f(i);
  if (fi == c) {
    j = i;
    break;
  }
}

还是这个?

for (i = a; (i <= b) && (IsFound == 0); i++) {
  fi = f(i);
  if (fi == c) {
    j = i;
    IsFound = 1;
  }
}

我会选择第一种方式,因为:

  • 其次,您定义了一个新变量 isFound 并维护它。
  • 您通过检查每个 i 值的 isFound 变量来增加开销。
  • 您将在末尾进行额外的检查和递增,因为 isFound 变量您将中断 for 循环。

快速回答:break; 更好

为什么,一旦到达 break,代码就会跳出循环。但是在第二个选择中你需要达到 for 循环条件检查状态

Quoting

The break statement terminates the execution of the nearest enclosing do, for, switch, or while statement in which it appears. Control passes to the statement that follows the terminated statement.

在代码解释中

选项一

for ( i = a; i <= b; i++ ){
  fi = f ( i );
  if ( fi == c ){
     j = i;
     break; // Simply exit from here , no more continuing
  }
}

选项二

for ( i = a; (i <= b) && (IsFound == 0); i++ ) // Need to reach here for exit
{
  fi = f ( i );    
  if ( fi == c ){
    j = i;
    IsFound = 1; // you set flag here but need to continue till for loop condition checking
  }
}

Break 是停止循环的最佳方式。

考虑一下,如果您在 if 条件之后做了很多工作,那么您有更多的代码。如果您在启用该条件后使用该变量,该条件将执行。 执行后没有从循环中出来。

如果你使用休息时间。那个时候循环本身就会中断。它从循环中出来。