What is the correct way to declare a main () function?

5

In some of the research I've done, I've noticed that there are some different ways of doing it, like the examples below:

int main()
int main(void)
void main()

// entre outros...

I know that the statements are entirely linked to the return commands, for example I need to return some integer in the int function type and that void does not return anything.

I would like a more detailed explanation as to the syntax and enforceability of these examples.

    
asked by anonymous 28.10.2015 / 17:44

1 answer

6

Both work on most compilers. It may depend on the attached option and the pattern you want to meet.

The recommendation is usually to use at least the C99 standard where these two forms are accepted:

int main(void)
int main(int argc, char *argv[])

But some prefer the C89 standard that is more compatible with non-modern compilers (rare, but found on embedded platforms). Then% w as% as a parameter can be avoided (no pun intended: P). If you follow the C ++ standard, it is also avoided.

Using void indicates that the function has no parameter . If it has nothing, it has an undefined parameter number and the implementation can have whatever parameters it wants. This can be confusing in some cases.

Return must always be void , although some compilers may accept other types, especially int . In C89 it is necessary to give void with an integer. In C99 this can be implicit, returning 0.

Remembering that some compilers may not be fully compliant and require a different form.

The best is the second. The first is acceptable almost always and the last one should not be used.

Specification:

  

5.1.2.2.1 Program startup

     

The function called at startup program is named main. The implementation declares no prototype for this function. It shall be defined with a return type of int and with no parameters:

     

int main (void) {/ * ... * /}   or with two parameters (referred to here as argc and argv, though any names may be used, as they are local to the function in which they are declared):

     

int main (int argc, char * argv []) {/ * ... * /}   or equivalent; or in some other implementation-defined manner.

    
28.10.2015 / 18:08