一个函数的返回数据类型,在main()中声明其原型为void。它包含一条return;指令,如下:
main()
{
void create(int *p);
*some code*
}
void create(node *list)
{
*some code*
return;
}
它会返回什么,以及它将在哪里返回?
一个函数的返回数据类型,在main()中声明其原型为void。它包含一条return;指令,如下:
main()
{
void create(int *p);
*some code*
}
void create(node *list)
{
*some code*
return;
}
这段代码不会返回任何值,但是你可以在无返回值函数中使用return语句来改变函数的流程并退出函数。例如,可以将以下代码:
void do_something(int i)
{
if (i > 1) {
/* do something */
}
/* otherwise do nothing */
}
你可能会遇到以下问题:
void do_something(int i)
{
if (i <= 1)
return;
/* if haven't returned, do something */
}
int a()
{
return 10;
}
void b()
{
return; // we have nothing to return, this is a void function.
}
void c()
{
// we don't need return; it is optional.
}
对于一个void函数,return语句是无用的,可以省略,是可选的。但有时它是有用的,例如退出循环或开关。
void xxx()
{
int i = 0;
while (1)
{
if (++i >= 100)
return; // we exit from the function when we get 100.
}
}
return;
不会返回任何东西,这与函数create
声明的void
返回类型相匹配。它将返回到调用它的函数(在你的示例中未显示),就像return EXPRESSION;
一样。
在这段特定的代码中,return;
是多余的,因为它出现在create
的末尾,但当你想要提前退出函数时,它是有用的:
void print_error(char const *errmsg)
{
if (errmsg == NULL)
// nothing to print
return;
perror(errmsg);
}
执行函数将返回一个void
返回值(表示没有值)。