Toby
Toby

Reputation: 10144

Returning void function from a void function

I can do the following:

static int16_t foo (void);

static int16_t bar (void) {
    return foo();
}

But my compiler complains about

static void foo (void);

static void bar (void) {
    return foo();
}

Does ANSI C not allow void functions to return void functions? why?

Upvotes: 3

Views: 330

Answers (3)

Jashaszun
Jashaszun

Reputation: 9270

If you want bar to return foo, then you have to change the return type of bar so that it returns a function that takes void and returns void instead of just void:

static (void (*)(void)) bar(void) {
    return foo;
}

Also, that first example shouldn't work either.

Edit based on your edit: you can't (shouldn't) return any data from a void function. void is the absence of data. In C, you can only return; from a function that is declared as returning void -- you can't return <data>; from it.

So foo() does not give you any data. It can only be used as a statement, not as an expression.

return foo(); therefore does not make sense in two ways: the first is that bar may not return anything as it is declared to return void, and the second is that even if bar does return an actual data type, foo() is still of type void and you cannot return that.

The first example works because both foo and bar return int16_ts, which are actual data.

Upvotes: 7

Deduplicator
Deduplicator

Reputation: 45654

It is an error to try to return a value from a function declared to not return a value.

Don't do that.

Also, I really hope your compiler complains about implicitly converting a function-pointer to an integer, though it will only be a warning and not an error.
Still, heed it!


Now after your edit (Calling the function instead of returning it), return expression; is still forbidden in void-functions (C++ allows it though, for generic programming).

Trying to do so with full warnings: http://coliru.stacked-crooked.com/a/63cc53e798062820

Standard quote (C11):

6.8.6.4 The return statement

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

Upvotes: 5

Franz Holzinger
Franz Holzinger

Reputation: 998

Your bar function does not return a void, but a void returning function. Your method must return a function pointer of void.

typedef void (*fptr)();

static fptr bar (void) {
    return foo;
}

Upvotes: 0

Related Questions