exit是 C/C++ 语言中的跳转语句,它采用整数(零或非零)来表示不同的退出状态。
C/C++中有两种退出状态:
- 退出成功:退出成功由exit(0)语句表示,表示程序成功终止,即程序已经执行,没有任何错误或中断。
#include
#include int main() { FILE* file; // opening the file in read-only mode file = fopen("myFile.txt", "r"); printf("File opening successful!"); // EXIT_SUCCESS exit(0); } 注意:创建一个名为“myFile.txt”的文件并在本地设备中运行代码以查看输出。
- 退出失败:退出失败由exit(1)表示,表示程序异常终止,即发生了一些错误或中断。我们可以使用 1 以外的不同整数来表示不同类型的错误。
#include
#include int main() { FILE* file; // open the file in read-only mode file = fopen("myFile.txt", "r"); if (file == NULL) { printf("Error in opening file"); // EXIT_FAILURE exit(1); } // EXIT_SUCCESS exit(0); }
让我们看看这两种说法之间的区别——
exit(0) | exit(1) |
---|---|
Reports the successful termination/completion of the program. | Reports the abnormal termination of the program. |
Reports the termination when the program gets executed without any error. | Reports the termination when some error or interruption occurs during the execution of the program. |
The syntax is exit(0); | The syntax is exit(1); |
The usage of exit(0) is fully portable. | The usage of exit(1) is not portable. |
The macro used for return code 0 is EXIT_SUCCESS | The macro used for return code 1 is EXIT_FAILURE |
EXIT_SUCCESS is defined by the standard to be zero. | EXIT_FAILURE is not restricted by the standard to be one, but many systems do implement it as one. |
想要从精选的视频和练习题中学习,请查看C++ 基础课程,从基础到高级 C++ 和C++ STL 课程,了解基础加 STL。要完成从学习语言到 DS Algo 等的准备工作,请参阅完整的面试准备课程。