knowledge
knowledge

Reputation: 1025

C int main() vs. int main(void)

As far as I know int main(void) is demanded by C99 an C11 standards. So int main() is not correct for the main function in this standards.

But which C (not C++) standard allows a int main() definition of the main function?

Thanks and regards Alex

Upvotes: 4

Views: 1591

Answers (3)

Magnus Lutz
Magnus Lutz

Reputation: 598

If you are still unsure what to use after the other answers, i would recommend to have a define for empty parameters:

#if 0
 #define NO_PARAM
#else
 #define NO_PARAM void
#endif

in case of the main function you could then write

int main(NO_PARAM){
...
}

If you then change your mind later, you can simply use the preferred define without having the need to change all function signatures - which shall have no parameters - by hand.

Upvotes: 0

Pedro Isaaco
Pedro Isaaco

Reputation: 404

According to C89 (http://web.archive.org/web/20030222051144/http://home.earthlink.net/~bobbitts/c89.txt) the main method is defined in two ways

int main(void)
{
    // ...
}

or

int main(int argc, char *argv[])
{
    // ...
}

As far as I know this is the first standard definition, so I would assume int main() is only defined well in the C++ standard.

However, I still use it :)

Upvotes: 1

Jens Gustedt
Jens Gustedt

Reputation: 79003

I personally clearly prefer the version with (void), because it is usually better to declare functions with a prototype. But the form int main() { ... } is correct, too, as long as you use it in a definition and not a declaration, and in fact the C standard uses this form in a number of examples.

Here this defines and declares a function with no prototype, but for a definition it is clear that that function doesn't receive any arguments.

If you are trying to give a forward declaration of main, you shouldn't use that form, because there would be no warning if you called the function incorrectly. Here C and C++ are also different since C allows you to call main yourself, even recursively, where C++ forbids such things.

Upvotes: 4

Related Questions