Search code examples
crecursionreturnvoid

Recursive C void function and return keyword


Does someone know the internal differences between :

void RecFoo1(int bar){
  if (bar == 0)
    return ;
  RecFoo1(bar - 1);
}

and

void RecFoo2(int bar){
  if (bar == 0)
    return ;
  return RecFoo2(bar - 1);
}

I am convinced that it is always better to put the return keyword. If the recursive function is not a void function, one will get a warning from -Wreturn-type. But are these two piece of code compiled/executed the same way or not ? What are the internal differences for the machine ?

My example of function is stupid but it constitute a kind of minimal example...


Solution

  • The C standard is quite clear on this, your RecFoo2 example is not a valid C program:

    6.3.2.2 void

    The (nonexistent) value of a void expression (an expression that has type void) shall not be used in any way, ...

    and

    6.8.6.4 The return statement

    Constraints

    A return statement with an expression shall not appear in a function whose return type is void.