有没有办法在void函数中结束程序?

时间:2016-02-11 08:31:51

标签: c++

我想知道您是否可以在 void function 中结束程序。我知道使用void()时,你不能只做return 0,那么有什么能让我早点结束我的节目呢?

以下是一些帮助您了解我的情况的代码:

void checkInput(int a) {
    if (a is negative) {
        cout << "Your number can't be negative" << endl;
        // exit program
    }
    else {
        // move on to calculate square root function
    }
}

我在这里要做的是模拟一个问题,函数checkInput()将检查并查看数字是否为负数,然后进入下一个函数,实际上执行数字的平方根,所以我想确保它不是负面的。如果是否定的,我想退出程序。这只是一个示例程序。

4 个答案:

答案 0 :(得分:2)

从功能中提前退回

return;

对于early terminate进程(异常终止)

std::terminate();

对于early exit(&#34;正常&#34;终止)

std::exit(0); // or some other error code

最终,定义允许程序在main完成后结束的流控制可能更好。

答案 1 :(得分:1)

您可以使用C exit

void checkInput(int a) {
  if (a is negative) {
    cout << "Your number can't be negative" << endl;
    exit (EXIT_FAILURE);
    ^^^^^^^^^^^^^^^^^^^^
  } else {
    // move on to calculate square root function
  }
}

答案 2 :(得分:0)

一个关键字和一个分号:

return;

答案 3 :(得分:0)

您可以使用exit功能。它需要一个参数,它是将返回给shell的程序的返回值。此功能包含在<stdlib.h>

但是,更好的方法是将返回值添加到checkInput,因为在函数中间使用exit是意大利面条代码。