Lew Pitcher <> writes:
> On January 12, 2010 14:12, in comp.lang.c, wrote:
>
>> K&R 2nd edition, page no. 26, says that a function need not return a
>> value; a return statement with no
>> expression causes control, but no useful value, to be returned to the
>> caller......
>>
>> So according to above statement, is the following code correct?
>
> No. You misunderstand the statement in K&R
I don't think he did. At that point, K&R hadn't introduced void
functions.
In fact, it's legal for a non-void function to fall off the end -- but
if the caller attempts to use the result, the behavior is undefined
(C99 6.9.1p12).
In C99, a return statement with an expression may only appear in a
non-void function, and a return statement without an expression may
only appear in a void function (C99 6.8.6.4p1). In C90, which is what
K&R2 describes, a return statement without an expression ("return;")
may appear legally in a non-void function (C90 6.6.6.4).
> A function need not return a value. Those functions that do not return a
> value must be declared or defined as returning void. Functions that return
> void cannot return a value using the return statement.
>
> Functions that return a value must be declared or defined as returning a
> value of a specific type. Functions that return a value of a specific type
> must (pedants? am I correct here, or is there an implicit return value?)
> return the value using the return statement.
There's only an implicit return value in the special case of main, and
that's only in C99.
>>
>> #include<stdio.h>
>> int fun()
>> {
>> return;
>> }
>> int main()
>> {
>> printf("%d\n",fun());
>> return 0;
>> }
>>
>> Here, although no useful value is returned by fun(), but can main use
>> that value in printf()? Will it be UB?
>
> IFAIK, yes.
Yes, that's undefined behavior in C99 (I'm not sure about C90, but
it's certainly a bad idea).
Remember that pre-ANSI C didn't have void, so the usual way to define
a function that doesn't return a useful value was to leave off the
return type, letting it default to int:
do_something() /* implicitly returns int */
{
/* ... */
}
...
do_something(); /* function returns garbage int value,
which is ignored */
In effect, there's an implicit contract between the caller and the
function: the function doesn't return a result, and the caller doesn't
attempt to use it. In pre-ANSI C, there was no way to express or
enforce this contract. ANSI added "void" for this purpose. C90 and
C99 continue to permit falling off the end of a non-void function to
avoid breaking old code like this.
--
Keith Thompson (The_Other_Keith)
kst- <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"