C++中的退出函数

介绍

今天我们将学习C++中的exit()函数。我们知道可以使用内置的break函数来跳出循环。类似地,我们还可以使用exit()函数来退出整个C++程序。

想象一种情况,即在程序中需要得出结论。在整个程序编译或评估之前,你获得结果并得出了一些结论。

当你获得所需的信息或结果后,你如何立即终止程序?

上述问题的答案是使用C++中的内置exit()函数。所以让我们更仔细地看一下这个函数以及它的工作原理。

在C++中,exit()函数的定义是什么?

Flow Chart Representation Of Exit Function

理论上,C++中的exit()函数会导致相应的程序在函数被遇到时立即终止,无论它在程序清单中出现的位置如何。该函数在stdlib.h头文件下进行了定义,在使用exit()函数时必须包括该头文件。

C++中exit()函数的语法

使用exit()函数的语法如下所示。

exit( exit_value );

在这里,exit_value是程序成功终止后传递给操作系统的值。这个值可以在批处理文件中进行测试,其中ERROR LEVEL给出了exit()函数提供的返回值。通常,值为0表示成功终止,而任何其他数字则表示出现了错误。

C++中exit()函数的工作原理

记住,函数exit()从不返回任何值。它终止进程并执行终止程序的常规清理工作。

同时,在C++中调用此函数时,自动存储对象不会被销毁。

请仔细看下面的例子:

#include<iostream>
using namespace std;
int main()
{
	int i;
	cout<<"Enter a non-zero value: ";  //user input
	cin>>i;
	if(i)    // checks whether the user input is non-zero or not
	{
		cout<<"Valid input.\n";
	}
	else
	{
		cout<<"ERROR!";  //the program exists if the value is 0
		exit(0);
	}
	cout<<"The input was : "<<i;
}

输出:

Enter a non-zero value: 0
ERROR!
  • Since the user input for the above code provided is zero(0), the else part is executed for the if-else statement. Further where the compiler encounters the exit() function and terminates the program.
  • Even the print statement below the if-else is not executed since the program has been terminated by the exit() function already.

现在让我们来看另一个示例,我们试图确定一个数字是否为质数。

在C++中使用exit()函数

下面的程序演示了exit()函数的使用。

#include<iostream>
using namespace std;
int main()
{
	int i,num;
	cout<<"Enter the number : ";
	cin>>num;
	for(i=2;i<=num/2;i++)
	{
		if(num%i==0)
		{
			cout<<"\nNot a prime number!";
			exit(0);
		}
	}
	cout<<"\nIt is a prime number!";
	return 0;
}

输出:

Exit Example Output

进一步说,关于上述代码,

  • firstly we took a user input for the number. We need to check whether this number,num is prime or not.
  • After that, we apply a for loop which works from 2 to n/2. This is because we already know that all numbers are divisible by 1 as well as a number is indivisible by numbers above its half.
  • Inside the for loop, we check whether the number is divisible by the loop iterator at that instant. If so, we can directly conclude that the number is not prime and terminate the program using the exit() function,
  • Else, the loop goes on checking. After the execution of the whole loop structure, we declare the number as a prime one.

结论

在本教程中,我们讨论了C++中内置的exit()函数的工作原理和用法。它被广泛用于终止程序的执行。

如有任何问题,请在下方评论。

参考资料

  • https://stackoverflow.com/questions/461449/return-statement-vs-exit-in-main
  • /community/tutorials/c-plus-plus
广告
将在 10 秒后关闭
bannerAds