Search code examples
cfunctionreturnvoid

return statement in void function in C


In the following program, Why compiler does not gives any error or warning?

cc -Wall -pedantic my_program.c

code here:

#include <stdio.h>

void f()
{
        return; // return statement in void function
}

int main()
{
        f();
        return 0;
}

I have compiled the program in GCC compiler on Linux platform.


Solution

  • Of course you can use return; in a void function. How else would you return early from such a function?

    In your case the statement is redundant as it's reached on all control paths, but a compiler will certainly not issue a diagnostic in that instance.

    (Note that you must return explicitly from a non-void function, with the exception of main(), where a compiler must generate return 0; if missing.