Returning a void value
Author Message
Returning a void value

Can a function return void as if it was a real value?

extern void f(int);

void g(int x)
{
return f(-x);

Quote:
}

--

Mon, 05 Nov 2001 03:00:00 GMT
Returning a void value

Quote:

> Can a function return void as if it was a real value?

> extern void f(int);

> void g(int x)
> {
>   return f(-x);
> }

No; it's not legal and is meaningless -- a function declared as type void
has no return value.

If you are only interested in side-effects (not return values) of the
functions, use:

extern void f(int);

void g(int x) {
f(x);

Quote:
}

or even:

extern struct foo *f(int);

void g(int x) {
if (f(x) != NULL)
return; /* N.B. no value */
else
(void)f(x/2);

Quote:
}

Conversely, if you need to propagate a return value, your functions need to
be declared and implemented with a return type or some other mechanism
(e.g. global variables):

extern float f(int);

double g(int x) {
return (double)f(x);

Quote:
}

--

Mon, 05 Nov 2001 03:00:00 GMT
Returning a void value
Any function declared as void means that it will not return a value. void
is not a value, it is a syntactic construct in this context.
Mitch

Quote:
> Can a function return void as if it was a real value?

> extern void f(int);

> void g(int x)
> {
>   return f(-x);
> }
> --

--

Fri, 09 Nov 2001 03:00:00 GMT
Returning a void value

Quote:
> > Can a function return void as if it was a real value?

Quote:
> No.  Void means nothing is returned.

Right.  But he should have quitt (sorry) while he was ahead, because he
continues:

Quote:
> You can return a NULL pointer, or a void pointer (pointer to void).

Not from a function declared to return void, you can't.  Section 6.6.6.4:

#  Constraints
#
#  A return statement with an expression shall not appear in a function
#  whose return type is void.
--
Mark Brader, Toronto                                "'Run me,' Alice?"

--

Fri, 09 Nov 2001 03:00:00 GMT
Returning a void value

Quote:

> No; it's not legal and is meaningless -- a function declared as type void
> has no return value.

That's what I thought.

In my program, the functions were originally defined to return int.
Then I changed the return types to void and recompiled successfully.
To my surprise, I then noticed I had forgotten to remove the "return"
in the calling function.  Yet, "gcc -Wall -W" had compiled it without
complaints.

It does complain with "-pedantic", though.
--

Fri, 09 Nov 2001 03:00:00 GMT
Returning a void value

Quote:

> Can a function return void as if it was a real value?

> extern void f(int);

> void g(int x)
> {
>   return f(-x);
> }

`void' means that the function returns nothing. It is impossible to return
something while returning nothing.

--

--

Fri, 09 Nov 2001 03:00:00 GMT

 Page 1 of 1 [ 6 post ]

Relevant Pages