-1

In C when a function has a return type of say int and I do not include a return call in the function I only get a warning.

Is this acceptable?

int foo()
{
    int number = 0;
}

What would the return value be?

james82345
  • 530
  • 4
  • 13

1 Answers1

5

Standard section 6.6.3 includes the rule:

A return statement with neither an expression nor a braced-init-list can be used only in functions that do not return a value, that is, a function with the return type void, a constructor (12.1), or a destructor (12.4). A return statement with an expression of non-void type can be used only in functions returning a value; the value of the expression is returned to the caller of the function. The value of the expression is implicitly converted to the return type of the function in which it appears. A return statement can involve the construction and copy or move of a temporary object (12.2). A return statement with a braced-init-list initializes the object or reference to be returned from the function by copy-list-initialization (8.5.4) from the specified initializer list.

Flowing off the end of a function is equivalent to a return with no value; this results in undefined behavior in a value-returning function.

Note that this is only a problem if the closing brace of the function is reachable. If execution always takes a branch that does have a return {value}, there is no problem.

Community
  • 1
  • 1
Ben Voigt
  • 277,958
  • 43
  • 419
  • 720