返回1,返回0,返回-1和退出之间的区别? [英] Difference between return 1, return 0, return -1 and exit?

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

问题描述

例如考虑以下代码:

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\n");
        return 1;
}


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

   return 0;
}

在上述程序中return 0return 1exit(0)有什么作用? exit(0)将退出整个程序,并且控制退出循环,但是在return 0return 1return -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来自main()等同于exit

程序将以退出状态设置为传递给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.

状态0表示程序成功.

状态不同于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\n");
    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.

值得一提的是,如果您尝试执行一些无效的操作(例如读取您无法访问的内存),则OS本身可能会使用特定的退出状态代码来终止程序.

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.

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

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