为什么 main() 需要大括号?
我尝试了
main() return;
or
main() if();
的几种变体,并获得了不同的错误,其中最奇特的是,
/usr/lib/gcc/i686-linux-gnu/4.4.5/../../../../lib/crt1.o: In function `_start': (.text+0x18): undefined reference to `main' collect2: ld returned 1 exit status
虽然程序只需要一个语句是不常见的,但为什么 main() 要求有大括号?
有人可以解释为什么在编译 int main(); 时错误如此奇特吗?
I tried several variations on
main() return;
or
main() if();
and obtained different errors, the most peculiar of which was
/usr/lib/gcc/i686-linux-gnu/4.4.5/../../../../lib/crt1.o: In function `_start': (.text+0x18): undefined reference to `main' collect2: ld returned 1 exit status
While it's uncommon for a program to require only one statement, why does main() make it a requirement to have braces?
Could someone explain why the error was so peculiar when compiling just int main();?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
因为您正在定义一个名为
main()
的函数,并且函数定义基本上是一个函数声明(int main()
部分),后跟一个复合语句(>{ /* ... */ }
部分)(您还可以使用函数 try 块,但这些很少使用,并且仍然需要大括号)。没有大括号就不能定义任何函数。
Because you are defining a function named
main()
and a function definition is basically a function declaration (theint main()
part) followed by a compound statement (the{ /* ... */ }
part) (you could also use a function try block, but those are very rarely used and still require braces).You can't define any function without braces.
这并不是 main 所独有的——任何函数体都必须用大括号括起来。具体来说,§8.4/1 将函数体定义为“复合语句”(对于真正迂腐的人来说,§6.3/1 将复合语句定义为: “{ 语句-seqopt }”。
It's not unique to main -- the body of any function must be surrounded by braces. Specifically §8.4/1 defines a function-body as a "compound-statement" (and, for the truly pedantic, §6.3/1 defines a compound-statement as: "{ statement-seqopt }".
因为它是一个函数。它是语法的一部分。
Because it is a function. It's part of the syntax.
因为 C++ 标准规定所有带有函数体的函数都必须有大括号。这就是标准的定义方式,无论好坏。
Because the C++ standard says that all functions with a body must have braces. That's just the way the standard is defined, for better or for worse.