Why does main() require braces?

烂漫一生 提交于 2019-12-08 01:22:58

问题


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();?


回答1:


Because you are defining a function named main() and a function definition is basically a function declaration (the int 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.




回答2:


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 }".




回答3:


Because it is a function. It's part of the syntax.




回答4:


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.



来源:https://stackoverflow.com/questions/5138609/why-does-main-require-braces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!