'what is the reason behind getting the "invalid use of void expression" error in C?
I have this piece of C code here :-
#include<stdio.h>
void message();
int main()
{
message(message());
return 0;
}
void message()
{
printf("hello\n");
}
The compiler throws an error message reading " Invalid use of void expression" for the statement block "message(message))".
I expected the output to be two times the printf() statement as according to me, the statement message(message()); indicates that once the inner function call executes and the control returns to main and after that again the outer call executes. However I am getting the error message "Invalid use of void expression" error here.
I have read some explanations but still i'm unable to understand.
Solution 1:[1]
The return type of the function message is void
void message();
So calling the function passing an argument of the incomplete type void invokes an error.
message(message());
If you want to call the function twice then write
message();
message();
or as one expression
message(), message();
Pay attention to that it is better to declare the function like
void message( void );
providing to the compiler the function prototype.
If you want to call the function specifying its argument as a call of it itself then the function should be declared and defined the following way
const char * message( const char *s )
{
puts( s );
return s;
}
and the function can be called like
message( message( "hello" ) );
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
