理解C语言的exit与return

exit

    在/usr/include/stdlib.h中,C语言定义了2种常规退出状态(exit status),分别是EXIT_FAILURE和EXIT_SUCCESS:

...
/* We define these the same for all machines.
   Changes from this to the outside world should be done in `_exit'.  */
#define EXIT_FAILURE    1       /* Failing exit status.  */
#define EXIT_SUCCESS    0       /* Successful exit status.  */
...

    从网络引用如下示例,如果不存在data.txt文件,则退出状态为失败,退出值为1;如果存在data.txt文件,则输出“Normal Return”,退出状态为成功,退出值为0。

#include <stdio.h>
#include <stdlib.h>
 
int main(void)
{
    FILE *fp = fopen("data.txt","r");
    if (fp == NULL)
    {
       fprintf(stderr,"fopen() failed in file %s at line # %d\n", __FILE__,__LINE__);
       exit(EXIT_FAILURE);
    }
 
    /* 正常进程持续至此。 */
    fclose(fp);
    printf("Normal Return\n");
 
    return EXIT_SUCCESS;
}

    用户可以自定义不同的退出值,但是要注意取值范围,取值范围为0~255,超过这个范围,就会截取二进制退出值的低8位字符,可以理解为最终得到退出值与256的余数。示例如下,当设置返回值为256时,实际却返回0:
exit_256.c

#include<stdlib.h>
int main(void)
{
    exit(256);
}

    编译执行

# gcc exit_256.c -o exit_256
# ./exit_256
# echo $?
0

    一般惯例是保留128及更高的状态值,以用于特殊目的。值128用于指示在子过程中无法执行另一个程序。该约定只是建议,非必须遵守。

return

    在C语言中,函数定义包含返回类型、函数名和参数,如下图所示:
在这里插入图片描述
    根据是否需要返回值与是否需要参数,可以将函数分为4类:无参数无返回值、有参数无返回值、无参数有返回值和有参数有返回值。
在这里插入图片描述
    当函数返回类型为void时,函数无返回值,函数定义中无需使用return语句;当函数返回类型不为void时,函数有返回值,函数定义中需要使用return语句,并且return类型必须与函数返回类型一致。下面示例来自网站GeeksforGeeks,在示例中,Print()函数返回void类型的空值,所以不适合使用return语句,如果使用,return后不应该有值,否则会报错。

// C code to show using return 
// statement in void return type function 

#include <stdio.h>  

// void method 
void Print()  
{  
    printf("Welcome to GeeksforGeeks");

    // void method using the return statement 
    return;  
}       

// Driver method 
int main()  
{       
    // Calling print 
    Print();
    return 0;
}  

    如果将Print()函数中的return改为exit,程序会在执行完Print()函数直接退出,不会跳转回main函数。修改后的程序如下,执行程序时不打印Print()函数后的语句,程序退出值为1:

#include <stdio.h>  
#include <stdlib.h>

// void method 
void Print()  
{      
    printf("Now in Print function.\n");  
    // void method using the exit statement
    exit(EXIT_FAILURE);
}       

// Driver method 
int main()  
{          
    // Calling print
    Print();    
    printf("Now in main function.\n");
    return EXIT_SUCCESS;
}   

    return除了可以返回数值,还可以返回指针。根据网络资料,编写下面小程序,比较2个字符串的长短,输出较短的字符串:

#include<stdio.h>

char *smallstr( char s1[], char s2[] )
{
    int i;

    i = 0;
    while ( s1[i] != '\0' && s2[i] != '\0' )
        i++;
    if ( s1[i] == '\0' )
        return ( s1 );
    else
        return ( s2 );
}

int main(void)
{
    char char1[]="Hello python";
    char char2[]="Hello C";
    char *pointer=char1;
    int number=0;

    pointer=smallstr(char1,char2);
    for(;pointer[number] != '\0';number++)
    {   
        printf("%c",pointer[number]);
    }   
    printf("\n");
}

    编译运行,可得到结果“Hello C”。

区别

个人总结exit和return的区别如下:

  • 退出程度不同。虽然都是退出并返回值,但exit退出整个程序,return退出当前函数。
  • 返回值类型不同。exit只返回简单的数值,return稍复杂,可以返回数值、指针、结构体等格式。return返回结构体的示例,见C - Function returning structure

参考文档

[1]GNU.Exit Status[EB/OL].https://www.gnu.org/software/libc/manual/html_node/Exit-Status.html,2020-01-01.
[2]Fruderica.EXIT_SUCCESS, EXIT_FAILURE[EB/OL].https://zh.cppreference.com/w/c/program/EXIT_status,2017-12-09.
[3]Chinmoy Lenka.return statement in C/C++ with Examples[EB/OL].https://www.geeksforgeeks.org/return-statement-in-c-cpp-with-examples/?ref=rp,2020-01-01.
[4]Shivani Baghel 1.C function argument and return values[EB/OL].https://www.geeksforgeeks.org/c-function-argument-return-values/,2020-01-01.
[5]corob-msft,Saisang,Mikejo5000,NextTurn,ghogen.Return Type[EB/OL].https://docs.microsoft.com/en-us/cpp/c-language/return-type?view=vs-2019,2016-11-04.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章