Anjan Anjan - 3 months ago 22
C Question

return type in C

If we do not specify a return type, compiler assumes an implicit return type as

int
. I tried to return a
char
and it worked fine in GCC. I just defined it like this

#include <stdio.h>

char fun(char ch)
{
return ch;
}

int main()
{
char ch = fun('A');
printf("ch : %c\n",ch);
}


But, In below program not specify a return type, but

#include <stdio.h>

char fun(char ch)
{

}

int main()
{
char ch = fun('A');
printf("ch : %c\n",ch);
}


and it worked fine means return a
char
. Why?

Why not return
int
return type by default?

Answer

As it has been pointing out, it seem that the goal of a return value has been misunderstood.

Function declarations

when declaring a function you are not forced to give it a body, you are telling the compiler that somewhere in the full program there will be such function.

This :

char fun(char ch);
int main()
{
    char ch = fun('A');
}

Is still valid C, and compile ( to an object file )

By doing this you are telling the compiler that the function does not exists now but should exists later. This is quite helpful when using library or other object files to be linked to form your final program.

unfortunately C compilers are still not smart enough to infer what was exactly your intention if you write

int main()
{
    char ch = fun('A');
}

it will try to best guess by defaulting to a mostly wrong type for your fun, or just stop because guessing would be wrong.

One practical example to this would be

func.c

char fun(char ch)
{
    return ch;
}

Compile with cc -c fun.c will compile a fun.o object file

main.c

#include <stdio.h>

char fun(char ch); // fun exist in fun.c but not in main.c this is a way yo tell that the function exists

int main()
{
    char ch = fun('A');
    printf("ch : %c\n",ch);
}

Compile with cc -c main.c will compile a main.o object file

then link the two files with cc fun.o main.o -o main, it will link the two object file into the program main.

return statement

the return statement have two goal

  • set the value to be send to the caller
  • stop the execution flow of the current function and return to the caller execution flow

in your function prototype you will have to declare what your function would return. which seems quite some extra code when having only one return statement per function, but what would make sure you are keeping your promise ?

What if you have two return statement in your function, ... returning different type? what should be the inferred type of your function?

What if you are returning an int should the computer store it in the char? what if the char is too big? what if you return a struct instead?