Why and how does GCC compile a function with a missing return statement?

后端 未结 8 1022
萌比男神i
萌比男神i 2020-12-01 23:57
#include 

char toUpper(char);

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


        
8条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-02 00:35

    I have tried a small programm:

    #include 
    int f1() {
    }
    int main() {
        printf("TEST: <%d>\n",  f1());
        printf("TEST: <%d>\n",  f1());
        printf("TEST: <%d>\n",  f1());
        printf("TEST: <%d>\n",  f1());
        printf("TEST: <%d>\n",  f1());
    }
    

    Result:

    TEST: <1>

    TEST: <10>

    TEST: <11>

    TEST: <11>

    TEST: <11>

    I have used mingw32-gcc compiler, so there might be diferences.

    You could just play around and try e.g. a char function. As long you don't use the result value it will stil work fine.

    #include 
    char f1() {
    }
    int main() {
        f1();
    }
    

    But I stil would recommend to set either void function or give some return value.

    Your function seem to need a return:

    char toUpper(char c)
    {
        if(c>='a'&&c<='z')
            c = c - 32;
        return c;
    }
    

提交回复
热议问题