int main()有什么问题? [英] What's wrong with int main()?

查看:577
本文介绍了int main()有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法计算我在那里看到C代码的次数,在这里SO中将 main 定义为

I can't count the number of times I've seen C code out there and here on SO that defines main as

int main() { ...

当我用

gcc -ansi -pedantic -Wstrict-prototypes -Werror foo.c

出现错误

foo.c:2: warning: function declaration isn't a prototype

那是为什么

int main(void)

是否需要使错误消失?

推荐答案

因为定义

int main() { /* ... */ }

不包括原型;它没有指定参数的数量或类型.

does not include a prototype; it doesn't specify the number or type(s) of the parameters.

此:

int main(void) { /* ... */ }

包含一个原型.

带空括号的意思是main带有固定但未指定的数量和类型的参数.使用(void)时,您明确地说它需要 no 个参数.

With the empty parentheses, you're saying that main takes a fixed but unspecified number and type(s) of arguments. With (void), you're explicitly saying that it takes no arguments.

与前者一样,呼叫如下:

With the former, a call like:

main(42);

不一定会被诊断.

这可以追溯到ANSI之前的日子,即在将原型引入该语言之前,并且大多数函数都用空括号定义.那时,编写以下内容完全合法:

This goes back to the pre-ANSI days before prototypes were introduced to the language, and most functions were defined with empty parentheses. Back then, it was perfectly legal to write:

int foo();

int foo(n)
int n;
{
    /* ... */
}

...

foo(42);

将原型添加到该语言(从C ++借用)后,有必要保留空括号的旧含义;添加了"new"(这是1989年)语法(void),因此您可以明确地说一个函数不带参数.

When prototypes were added to the language (borrowed from C++), it was necessary to keep the old meaning of empty parentheses; the "new" (this was 1989) syntax (void) was added so you could explicitly say that a function takes no arguments.

(C ++具有不同的规则;它不允许使用老式的非原型函数,并且括号为空表示函数不带参数.C ++允许(void)语法与C兼容,但通常不建议这样做)

(C++ has different rules; it doesn't allow old-style non-prototyped functions, and empty parentheses mean that a function takes no arguments. C++ permits the (void) syntax for compatibility with C, but it's not generally recommended.)

最佳实践是使用(void),因为它更明确.尚不清楚int main()格式是否有效,但我从未见过不接受它的编译器.

Best practice is to use (void), because it's more explicit. It's not entirely clear that the int main() form is even valid, but I've never seen a compiler that doesn't accept it.

这篇关于int main()有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆