GCC为什么以及如何使用缺少的return语句编译函数?

har*_*son 9 c linux gcc

#include <stdio.h>

char toUpper(char);

int main(void)
{
    char ch, ch2;
    printf("lowercase input : ");
    ch = getchar();
    ch2 = toUpper(ch);
    printf("%c ==> %c\n", ch, ch2);

    return 0;
}

char toUpper(char c)
{
    if(c>='a'&&c<='z')
        c = c - 32;
}
Run Code Online (Sandbox Code Playgroud)

在toUpper函数中,返回类型为char,但toUpper()中没有"return".并使用gcc(GCC)4.5.1 20100924(Red Hat 4.5.1-4),fedora-14编译源代码.

当然,发出警告:"警告:控制到达无效功能的结束",但是,运行良好.

在使用gcc编译期间,代码中发生了什么?在这种情况下,我想得到一个可靠的答案.谢谢 :)

Ray*_*oal 19

你发生的事情是,当C程序被编译成汇编语言时,你的toUpper函数就像这样结束了,也许:

_toUpper:
LFB4:
        pushq   %rbp
LCFI3:
        movq    %rsp, %rbp
LCFI4:
        movb    %dil, -4(%rbp)
        cmpb    $96, -4(%rbp)
        jle     L8
        cmpb    $122, -4(%rbp)
        jg      L8
        movzbl  -4(%rbp), %eax
        subl    $32, %eax
        movb    %al, -4(%rbp)
L8:
        leave
        ret
Run Code Online (Sandbox Code Playgroud)

减去32是在%eax寄存器中进行的.并且在x86调用约定中,这是预期返回值的寄存器!所以...你很幸运

但请注意警告.他们是有原因的!


Mat*_*ats 7

它取决于应用程序二进制接口以及哪些寄存器用于计算.

例如,在x86上,第一个函数参数和返回值存储在其中EAX,因此gcc最有可能使用它来存储计算结果.