Search code examples
cfunctiontypesreturnwarnings

what does a "warning: type defaults to ‘int’" function actually return?


foo.c:3:8: warning: type defaults to ‘int’ in declaration of ‘bar’ [-Wimplicit-int]

I encountered a warning when trying to compile these two files, which I knew was because I didn't specify the type of bar function at the beginning. But I wanted to figure out what the value returned by the default int return type actually represented. I tried to change the content of the bar function, including the number of parameters and function bodies (such as adding some short statements), but I didn't find any rules for the return value.

foo.c

#include<stdio.h>

extern bar();

int main()
{
        int a = 4;
        int ret = bar(a);
        printf("ret = %d\n",ret);
        return 0;
}

bar.c

#include<stdio.h>

void bar(int a)
{
        printf("a = %d\n",a);
}

compiled whth gcc -o fb foo.c bar.c

and the result

a = 4
ret = 6

Solution

  • What type the function returns and what value the function returns are separate things.

    In extern bar();, you have not declared the function to return void, which would mean nothing is returned. This means it returns something and, due to the history of the C language, the type of what it returns defaults to int.

    With such a declaration, the function should return an int value, if its return value is used.

    In this code:

    void bar(int a)
    {
            printf("a = %d\n",a);
    }
    

    you do not return a value. There is no return statement. But the return value is used in your main routine. The resulting behavior is not defined by the C standard. There are no rules in the C standard for what will happen.