什么时候使用 exit() 而不是 return?
When to use exit() over return?
我想知道什么时候应该使用 exit()
函数而不是 return
语句。我可以用以下任一语句结束程序:
exit(0);
or
return;
我应该在什么时候使用哪一个?
使用 exit()
有什么好处吗?
这两者在本质上是非常不同的。
exit()
用于立即终止程序。如果从应用程序的 any 部分遇到对 exit()
的调用,则应用程序结束执行。
return
用于return程序执行控制给caller函数。仅在 main()
的情况下,return
完成执行。
编辑:
澄清在 main()
中使用时的情况,直接引用 C11
标准,第 §5.1.2.2.3 章,程序终止 ,
If the return
type of the main()
function is a type compatible with int
, a return
from the initial call to the main()
function is equivalent to calling the exit()
function with the value returned by the main()
function as its argument;11) reaching the }
that terminates the
main()
function returns a value of 0
. If the return type is not compatible with int
, the termination status returned to the host environment is unspecified.
所以,基本上,要么
return 0;
exit(0);
将在 main()
的上下文中表现相同。
我想知道什么时候应该使用 exit()
函数而不是 return
语句。我可以用以下任一语句结束程序:
exit(0);
or
return;
我应该在什么时候使用哪一个?
使用 exit()
有什么好处吗?
这两者在本质上是非常不同的。
exit()
用于立即终止程序。如果从应用程序的 any 部分遇到对exit()
的调用,则应用程序结束执行。return
用于return程序执行控制给caller函数。仅在main()
的情况下,return
完成执行。
编辑:
澄清在 main()
中使用时的情况,直接引用 C11
标准,第 §5.1.2.2.3 章,程序终止 ,
If the
return
type of themain()
function is a type compatible withint
, areturn
from the initial call to themain()
function is equivalent to calling theexit()
function with the value returned by themain()
function as its argument;11) reaching the}
that terminates themain()
function returns a value of0
. If the return type is not compatible withint
, the termination status returned to the host environment is unspecified.
所以,基本上,要么
return 0;
exit(0);
将在 main()
的上下文中表现相同。