如何返回0并从函数终止

How do I return 0 and terminate from a function?

本文关键字:函数 终止 何返回 返回      更新时间:2023-10-16

在下面的代码中,如果function2中的"condition"小于3,我希望程序退出,但目前,它只是在switch语句之后继续执行代码。我如何着手实现我的目标?

#include <iostream>
using namespace std;
int main ()
{
    string answer;
    int selection;
    do
    {
        cin >> selection;
        switch(selection)
        {
            case 1:
            function1();
            break;
            case 2:
            function2();
            break;
            default:
            break;
        }
    cout << "Anything else?" << endl;
    cin >> answer;
    }while(!(answer == "no"));
    return 0;
}
void function1()
{   
    //do stuff
}
int function2()
{
    int condition;
    cin >> conditon;
    if(condition < 3)
    {
        cout << "That's an error." << endl;
        return 0;
    }
    return 0;
}

包括<stdlib.h>在你的头,把exit(0)而不是返回0,这对我来说是有效的:)