#include <iostream>
#include <cstdlib> // Needed to use the exit function
using namespace std;
// Function prototype
void someFunction();
int main ()
{
someFunction ();
return 0;
}
void someFunction()
{
cout << "This program terminates with the exit function. \n";
cout << "Bye!\n";
exit (0);
cout << "This message will never be displayed\n";
cout << "because the program has already terminated.\n";
}
程序输出结果:
This program terminates with the exit function.
Bye!
<cstdlib> 头文件。请注意,该函数釆用整数实参,这个实参是希望程序返回到计算机操作系统的退出代码。该代码有时在程序外部使用,以指示程序退出是成功结束还是故障的结果。exit(EXIT_SUCCESS);
当然,一般认为良好的编程实践是,尽可能在 main 函数结束时终止程序,所以,许多程序员仅使用 exit 函数来处理出错的情形。在这种情况下,应该使用错误代码来表明发生了问题。这可以通过使用另一个 C++ 命名常量 EXIT_FAILURE 来完成。在 cstdlib 中定义的这个命名常量被定义为:通常表示当前操作系统下未能成功退出的终止代码。以下是其使用示例:exit(EXIT_FAILURE);
提示,exit 函数将无条件地关闭程序。因为它绕过了程序的正常逻辑流程,所以应该谨慎使用它。
版权说明:Copyright © 广州松河信息科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州松河信息科技有限公司 版权所有