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等的更多准备工作,请参阅“完整面试准备课程” 。