我运行以下 C 代码并收到警告:控制到达非 void 函数的末尾
int main(void) {}
有什么建议吗?
只需将
return 0
放入您的 main()
中即可。你的函数 main 返回一个 int (int main(void)
) 因此你应该在它的末尾添加一个 return 。
控制到达非 void 函数的末尾
Problem: I received the following warning:
警告:控制到达非void函数的末尾
解决方案:该警告与Return with no value中描述的警告类似。如果控制到达函数末尾并且没有遇到返回,GCC 会假定返回没有返回值。然而,为此,该函数需要一个返回值。在函数末尾添加一个 return 语句,即使控制永远不会到达那里,它也会返回合适的返回值。
解决方案:
int main(void)
{
my_strcpy(strB, strA);
puts(strB);
return 0;
}
作为向
return
添加 main()
语句的明显解决方案的替代方案,您可以使用 C99 编译器(如果您使用的是 GCC,则为“gcc -std=c99”)。
在 C99 中,
main()
没有 return
语句是合法的,然后最终的 }
隐式返回 0。
$ gcc -c -Wall t.c
t.c: In function ‘main’:
t.c:20: warning: control reaches end of non-void function
$ gcc -c -Wall -std=c99 t.c
$
纯粹主义者认为重要的注意事项:您不应该通过将 main()
声明为返回类型
void
来修复警告。
所示
int main(void)
但是您的主函数不会返回任何内容,它会在
之后关闭
puts(strB);
添加
return 0;
之后就可以了。
f()
)调用错误处理程序(
error_handler()
),即永远不会返回的函数:
void error_handler(const char *msg) {
fprintf(stderr, "Houston, we have a problem (%s)\n", msg);
exit(1);
}
int f(int v) {
switch (v) {
case 1: return 42;
default: error_handler("unknown value");
/* for gcc it looks like if v != 1,
then there's no return statement,
but from the declaration it follows that
the function should return an int */
}
}
您可以使用 error_handler()
来声明 _Noreturn
:
_Noreturn void error_handler() {
...
解决警告。