return语句是否导致执行跳出当前执行的函数

Does the return statement cause the execution to jump out from the currently executed function?

本文关键字:执行 函数 是否 return 语句      更新时间:2023-10-16
bool accept3()
{
    int tries = 1;
    while (tries<4) {
        cout << "Do you want to proceed (y or n)?n"; // write question
        char answer = 0;
        cin >> answer; // read answer
        switch (answer) {
            case 'y':
                return true;
            case 'n':
                return false;
            default:
                cout << "Sorry, I don't understand that.n";
                ++tries; // increment
        }
    }
    cout << "I'll take that for a no.n";
    return false;
}

return语句是否导致执行跳出当前执行的函数(在本例中为accept3()),并且在返回后,它下面的代码将不运行,对吗?

return语句不关心您是否处于循环的中间。当你return某事时,你立即停止执行该函数

return语句将导致执行跳出当前执行的函数(在本例中为accept3()),因此函数内的循环也被跳出。

当存储在answer中的输入为y时,进入switch语句的第一个case,其中包含一个return true;,它从函数accept3()返回,从而也离开了while -循环。

因为return语句终止当前函数并将表达式的结果返回给调用者。While循环条件在本例中并不重要。