Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C/C++: Calling function with no arguments with function which returns nothing

Tags:

c++

c

Why isn't it possible to call a function which takes no arguments with a function call as argument which does not return any value (which IMHO is equivalent to calling a function which takes no arguments with no arguments).

For example:

void foo(void) {...}
void bar(void) {...}

foo(bar())

Don't get me wrong, I know void is not a value and that it cannot be treated like one.

With my logic it would make sense and it should be possible to do that. I mean, why not? Any argument why that should not be possible?

like image 701
George Avatar asked Jan 27 '10 01:01

George


People also ask

What is function with no arguments and no return value?

Example 1: No Argument Passed and No Return Value The return type of the function is void .

What happens if the function is called with no arguments given?

The C specification says that a function declared without any argument (not even a void argument) takes an unspecified number of arguments. If you want to explicitly say that a function takes no arguments, you need to specify a single void argument type without a name.

How do you call a function that returns nothing?

Void functions are created and used just like value-returning functions except they do not return a value after the function executes. In lieu of a data type, void functions use the keyword "void." A void function performs a task, and then control returns back to the caller--but, it does not return a value.

How do you call a function with no arguments in C?

To call a function which takes no arguments, use an empty pair of parentheses. Example: total = add( 5, 3 );


1 Answers

I'm not convinced that any of the reasons I've heard are good ones.

See, in C++, you can return a void function's result:

void foo() {
    // ...
}

void bar() {
    // ...
    return foo();
}

Yes, it's exactly the same as:

foo();
return;

but is much more consistent with generic programming, so that you can make a forwarding function work without having to worry about whether the function being forwarded has void return.

So, if a similar system applied so that a void return constituted a nullary call in a function composition scenario, that could make function composition more generic too.

like image 66
Chris Jester-Young Avatar answered Sep 29 '22 11:09

Chris Jester-Young