return 1、return 0、return -1 和 exit 的区别? [英] Difference between return 1, return 0, return -1 and exit?

查看:20
本文介绍了return 1、return 0、return -1 和 exit 的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如考虑以下代码:

int main(int argc,char *argv[])
{
   int *p,*q;
   p = (int *)malloc(sizeof(int)*10);
   q = (int *)malloc(sizeof(int)*10);
   if (p == 0)
{
    printf("ERROR: Out of memory
");
        return 1;
}


   if (q == 0)
{
    printf("ERROR: Out of memory
");
        exit(0);
}

   return 0;
}

上述程序中return 0return 1exit(0)是做什么的?exit(0) 将退出整个程序并且控制退出循环但是在 return 0return 1 的情况下会发生什么返回 -1.

What does return 0, return 1, exit(0) do in the above program? exit(0) will exit total program and control comes out of loop but what happens in case of return 0, return 1, return -1.

推荐答案

return from main() 等价于 exit

return from main() is equivalent to exit

程序立即终止执行,并将 exit status 设置为传递给 returnexit

the program terminates immediately execution with exit status set as the value passed to return or exit

return 将立即终止执行将给定结果返回给调用函数的特定函数.

return in an inner function (not main) will terminate immediately the execution of the specific function returning the given result to the calling function.

exit 从代码的任何位置都会立即终止程序执行.

exit from anywhere on your code will terminate program execution immediately.

status 0 表示程序成功.

status 0 means the program succeeded.

status 不为 0 表示程序因错误或异常而退出.

status different from 0 means the program exited due to error or anomaly.

如果你以不同于 0 的状态退出,你应该向 stderr 打印一条错误消息,所以不要使用 printf 更好的类似

If you exit with a status different from 0 you're supposed to print an error message to stderr so instead of using printf better something like

if(errorOccurred) {
    fprintf(stderr, "meaningful message here
");
    return -1;
}

请注意(取决于您使用的操作系统)有一些关于返回码的约定.

note that (depending on the OS you're on) there are some conventions about return codes.

Google 搜索退出状态代码"或类似信息,您会在 SO 和其他地方找到大量信息.

Google for "exit status codes" or similar and you'll find plenty of information on SO and elsewhere.

值得一提的是,如果您尝试执行一些无效操作,例如读取您无权访问的内存,操作系统本身可能会以特定的退出状态代码终止您的程序.

Worth mentioning that the OS itself may terminate your program with specific exit status codes if you attempt to do some invalid operations like reading memory you have no access to.

这篇关于return 1、return 0、return -1 和 exit 的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆