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

Asked

Viewed 2,455 times

7

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

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

// entre outros...

I know that statements are entirely linked to commands return, it is necessary for example to return some integer in the function type int and that the void nothing returns to me.

I would like a more detailed explanation of the syntax and the obligatory nature of these examples.

  • 1

    you already answered practically in your own question, what more explanation you want ? only left the type int main(void) to explain

  • 1

    Then detail what more you want detailed. See what is missing in my reply.

  • 1

    I’ve seen it void main(void) also =P

  • Maybe I haven’t been able to express myself correctly, but thank you very much for the answers.

  • @bigown was able to explain my question about which syntax pattern to use.

1 answer

8


Both work on most compilers. It may depend on the option on and the default 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 which is more compatible with non-modern compilers (rare, but found on embedded platforms). Here the void as a parameter can be avoided (no pun :P). If you follow the pattern of C++ it is also avoided.

The use of void indicates that the function has no parameter. If you have nothing, it has an undefined parameter number and the implementation can have the parameters you want. This can lead to confusion in some cases.

The return should always be int, although some compilers accept another type, especially the void. In C89 it is necessary to give the return with an integer number. In C99 this can be implied, it returns 0 for you.

Remembering that some compilers may not be fully in the pattern and require a different shape.

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

Specification:

5.1.2.2.1 Program startup

The Function called at program startup 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.

  • That’s exactly the explanation I was looking for! About the patterns.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.