返回语句和中断语句之间的区别

2022-08-31 11:54:44

语句与语句有何不同?
如果我必须退出 if 条件,我应该选择哪一个,或者 ?returnbreakreturnbreak


答案 1

break用于退出(转义)当前正在执行的 -loop、-loop、-语句。forwhileswitch

return将退出当前正在执行的整个方法(并可能向调用方返回一个值,可选)。

因此,要回答您的问题(正如其他人在评论和答案中指出的那样),您不能使用任何一个,也不能逃避-语句本身。它们用于转义其他作用域。breakreturnif-else


请考虑以下示例。-loop 内部的值将确定循环下方的代码是否将被执行:xwhile

void f()
{
   int x = -1;
   while(true)
   {
     if(x == 0)
        break;         // escape while() and jump to execute code after the the loop 
     else if(x == 1)
        return;        // will end the function f() immediately,
                       // no further code inside this method will be executed.

     do stuff and eventually set variable x to either 0 or 1
     ...
   }

   code that will be executed on break (but not with return).
   ....
}

答案 2

break在要退出循环时使用,而用于返回到调用它的步骤或停止进一步执行。return


推荐