C function defined as int but having no return statement in the body still compiles

后端 未结 7 2117
走了就别回头了
走了就别回头了 2020-11-28 13:48

Say you have a C code like this:

#include 

int main(){
    printf("Hello, world!\\n");
    printf("%d\\n", f());    
}

in         


        
相关标签:
7条回答
  • 2020-11-28 14:00

    The return value in this case, depending on the exact platform, will likely be whatever random value happened to be left in the return register (e.g. EAX on x86) at the assembly level. Not explicitly returning a value is allowed, but gives an undefined value.

    In this case, the 14 is the return value from printf.

    0 讨论(0)
  • 2020-11-28 14:04

    You probably have the warning level of your compiler set very low. So it is allowed, even if the result is undefined.

    0 讨论(0)
  • 2020-11-28 14:07

    compile with -Wall to enable more sanity checking in the compiler.

    gcc -Wall /tmp/a.c
    /tmp/a.c: In function ‘main’:
    /tmp/a.c:5: warning: implicit declaration of function ‘f’
    /tmp/a.c:6: warning: control reaches end of non-void function
    /tmp/a.c: In function ‘f’:
    /tmp/a.c:10: warning: control reaches end of non-void function
    

    Note how it flags up the missing return statements - as "control reaches end of non-void function"?

    Always compile using -Wall or similar - you will save yourself heartache later on.


    I can recall several occasions when this exact issue has caused hours or days of debugging to fix - it sorta works until it doesn't one day.

    0 讨论(0)
  • 2020-11-28 14:11

    18 is the return value of the first print statement. (the number of characters printed)

    This value is stored in stack memory.

    In second printf function the stack value is 'returned' by function f. But f just left the value that printf created in that slot on the stack.

    for example, in this code:

    #include <stdio.h>
    
    int main(){
        printf("Hello, world!1234\n");
        printf("%d\n", f());    
    }
    
    int f(){
    
    }
    

    Which compiles fine with gcc, and the output (on my system) is:

    Hello, world!

    18

    for details of printf() returning value mail me.

    0 讨论(0)
  • 2020-11-28 14:15

    I compile with -Werror=return-type to prevent this. GCC will give an error if you don't return from a function (unless it's void return).

    0 讨论(0)
  • 2020-11-28 14:18

    The default return value from a function is int. In other words, unless explicitly specified the default return value by compiler would be integer value from function.

    So, the ommiting of return statement is allowed, but undefined value will be returned, if you try to use it.

    0 讨论(0)
提交回复
热议问题