While reading the K&R 2nd edition I noticed that the programs always began with "main(){". I had always thought that main() had to have int or void before it. So that it would look like "int main()" or "void main()". What is just "main()" and what is the difference?
相关问题
- Multiple sockets for clients to connect to
- What does an “empty line with semicolon” mean in C
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
- Index of single bit in long integer (in C) [duplic
Because this is supported in by an old version of c.
is equivalent to
main()
is the old K&R style where theint
was omitted as the return type defaults toint
if not specified (you should specify it). Additionally, empty parentheses is in K&R style to show it takes no arguments.. in C99 this should now bevoid
to indicate such. Empty parentheses means that the function will accept any number of arguments of any type, which is clearly not what you want. So the final result is:main()
should returnint
.. convention says areturn 0;
statement at the end will help indicate to the caller that the program executed successfully - non-0 return values indicate abnormal termination.A more direct answer to your question would be that
main() { ... }
works because it's not wrong. The compiler sees that no return type was declared for themain
function so it defaults toint
. The empty parentheses indicates to it thatmain
takes any number of arguments of any type, which is not wrong either. However, to conform to C99 style/standard, useSyntax most of times depends on the compiler. For example, when you use visual c++ you write "void main" but when you use GCC, you should write "int main()" and then return 0 or 1 if the program finished good or bad.