Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicit int return value of C function

I've googled and just can't seem to find the answer to this simple question.

Working on a legacy code base (ported to Linux recently, and slowly updating to a new compiler) and I see a lot of

int myfunction(...) { // no return... } 

I know the implicit return TYPE of a function is int, but what is the implicit return VALUE when no return is specified. I've tested and gotten 0, but that's only with gcc. Is this compiler specific or is it standard defined to 0?

EDIT: 12/2017 Adjusted accepted answer based upon it referencing a more recent version of the standard.

like image 392
LeviX Avatar asked Apr 09 '12 20:04

LeviX


People also ask

What is the implicit return type of a function in C?

If some function has no return type, then the return type will be int implicitly. If return type is not present, then it will not generate any error. However, C99 version does not allow return type to be omitted even if it is int.

What is the default return value of C function?

If a return type isn't specified, the C compiler assumes a default return type of int . Many programmers use parentheses to enclose the expression argument of the return statement. However, C doesn't require the parentheses.

Can int be return type?

A return type may be a primitive type like int, float, double, a reference type or void type(returns nothing). The type of data returned by a method must be compatible with the return type specified by the method. For instance, if the return type of some method is boolean, we can not return an integer.


2 Answers

From the '89 standard as quoted in the new testament:

Flowing off the end of a function is equivalent to a return with no expression. In either case, the return value is undefined.

That standard usually expresses the on-the-ground behavior of pre-existing implementations.

like image 139
dmckee --- ex-moderator kitten Avatar answered Sep 29 '22 20:09

dmckee --- ex-moderator kitten


Such a thing is possible, but only under the assumption that the return value of the function is never used. The C11 standard says in para 6.9.1:

If the } that terminates a function is reached, and the value of the function call is used by the caller, the behavior is undefined.

(AFAIR previous version of the standard had similar wording)

So it would be a good idea to transform all the functions of that sort that you have to void functions, so no user of such a function could be tempted to use the return value.

like image 43
Jens Gustedt Avatar answered Sep 29 '22 19:09

Jens Gustedt