LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 2625|回复: 10

请问exit(1);和return 1; 有什么区别?

[复制链接]
发表于 2008-2-14 10:26:35 | 显示全部楼层 |阅读模式
请问exit(1);和return 1; 有什么区别?
发表于 2008-2-14 11:37:55 | 显示全部楼层
只有用于main函数的时候return和exit的作用才是相似的(不太确定是否相同)
回复 支持 反对

使用道具 举报

发表于 2008-2-14 12:48:05 | 显示全部楼层
return是函数返回时,返回的值。
exit是程序退出时,返回的值。
一个是返回函数,一个是退出程序。
以上是我的个人理解,希望对你有帮助。
回复 支持 反对

使用道具 举报

发表于 2008-2-14 15:35:17 | 显示全部楼层
exit是整个程序结束
return是本函数返回,如果碰巧是main函数,那才是整个程序结束
回复 支持 反对

使用道具 举报

 楼主| 发表于 2008-2-14 17:05:38 | 显示全部楼层
谢谢各位的指点!
回复 支持 反对

使用道具 举报

发表于 2008-2-18 14:01:18 | 显示全部楼层
另外 exit 非0值时 表 异常退出, exit 0 表正常退出
回复 支持 反对

使用道具 举报

发表于 2008-2-20 22:57:44 | 显示全部楼层
在每个C程序中的ctrl.o启动例程的伪代码如下:
1.   0x080480c0 <_start>:
2.      call _libc_init_first
3.      call _init
4.      call atexit
5.      call main
6.      call _exit
(上述伪代码参考:《深入理解计算机系统》)

对于main函数而言,
1)以return语句终止,控制传递给启动程序,然后通过调用_exit将控制返回给操作系统;
2)如果省略return语句,处理过程相同;
3)如果main以调用exit终止,同样最终会调用到_exit将控制返回给操作系统;

对于子函数而言,
调用exit同样是将控制返回给操作系统;return则是返回该函数的返回值;
回复 支持 反对

使用道具 举报

发表于 2008-2-25 21:59:43 | 显示全部楼层
C99 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;10) 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.

在main中return其实大体上相当于调用exit的。
回复 支持 反对

使用道具 举报

发表于 2008-3-20 16:46:55 | 显示全部楼层
And when you write void main(){},you can not use return.
Of course,we often use int main(){}
回复 支持 反对

使用道具 举报

发表于 2008-3-21 23:37:30 | 显示全部楼层
Post by shen.hen.en.n;1828803
And when you write void main(){},you can not use return.
Of course,we often use int main(){}


无论是 C 还是 C++,void main 都是错误的写法。
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表