C语言 为什么主函数会出现“控制到达非空函数结束”的警告?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13464243/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 04:29:27  来源:igfitidea点击:

Why a warning of "control reaches end of non-void function" for the main function?

c

提问by alittleboy

I run the following C codes and got a warning: control reaches end of non-void function

我运行以下 C 代码并收到警告:控制到达非空函数的结尾

int main(void) {}

Any suggestions?

有什么建议?

采纳答案by dreamcrash

Just put return 0in your main(). Your function main returns an int (int main(void)) therefore you should add a return in the end of it.

只需放入return 0您的main(). 您的函数 main 返回一个 int ( int main(void)) 因此您应该在它的末尾添加一个 return 。

Control reaches the end of a non-void function

控制到达非空函数的末尾

Problem: I received the following warning:

warning: control reaches end of non-void function

警告:控制到达非空函数的结尾

Solution: This warning is similar to the warning described in Return with no value. If control reaches the end of a function and no return is encountered, GCC assumes a return with no return value. However, for this, the function requires a return value. At the end of the function, add a return statement that returns a suitable return value, even if control never reaches there.

解决方案:此警告类似于无值返回中描述的警告。如果控制到达函数的末尾并且没有遇到返回,GCC 假定返回没有返回值。但是,为此,该函数需要一个返回值。在函数的末尾,添加返回合适的返回值的 return 语句,即使控制从未到达那里。

source

来源

Solution:

解决方案

int main(void)
{
    my_strcpy(strB, strA);
    puts(strB);
    return 0;
}

回答by Pascal Cuoq

As an alternative to the obvious solution of adding a returnstatement to main(), you can use a C99 compiler (“gcc -std=c99” if you are using GCC).

作为向 中添加return语句的明显解决方案的替代方案main(),您可以使用 C99 编译器(如果您使用的是 GCC,则为“gcc -std=c99”)。

In C99 it is legal for main()not to have a returnstatement, and then the final }implicitly returns 0.

在 C99 中main()没有return声明是合法的,然后 final}隐式返回 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
$ 


A note that purists would consider important: you should notfix the warning by declaring main()as returning type void.

一张纸条,纯粹主义者会认为重要的是:你应该不会通过声明固定预警main()为返回类型void

回答by Kninnug

The main function has a return-type of int, as indicated in

main 函数的返回类型为 int,如

int main(void)

however your main function does not return anything, it closes after

但是你的主函数没有返回任何东西,它在之后关闭

puts(strB);

Add

添加

return 0;

after that and it will work.

在那之后,它将起作用。