得到“无效使用 void 表达式”背后的原因是什么? C 中的错误?

发布于 2025-01-16 18:41:06 字数 394 浏览 8 评论 0原文

我这里有这段 C 代码:-

#include<stdio.h>
void message();
int main()
{
    message(message());
    return 0;
}
void message()
{
    printf("hello\n");
}

编译器抛出一条错误消息,读取语句块“message(message))”的“无效使用 void 表达式”。

我预计输出是 printf() 语句的两倍,根据我的说法,语句 message(message());表示一旦内部函数调用执行并且控制返回到 main,之后再次执行外部调用。但是,我在这里收到错误消息“无效使用 void 表达式”错误。

我已经阅读了一些解释,但仍然无法理解。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

断爱 2025-01-23 18:41:06

函数消息的返回类型是 void

void message();

因此调用传递不完整类型 void 的参数的函数会引发错误。

message(message());

如果要调用该函数两次,请将

message(); 
message();

or 写为一个表达式。

message(), message();

注意,最好像

void message( void );

向编译器提供函数原型一样声明该函数。

如果您想调用指定其参数作为其本身调用的函数,则应按以下方式声明和定义该函数

const char * message( const char *s )
{
    puts( s );

    return s;
}

,并且可以像这样调用该函数

message( message( "hello" ) );

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" ) );
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文