Why don't we use (void) in main?

People use void main() /*empty parens ()*/

I have been taught to write void main(void)

Any ideas what the difference is?


Solution 1:

I'm not sure what the standards are nowadays, but in traditional ANSI C, using empty parentheses indicates that the function can take any number of arguments. Declaring a void parameter on the other hand indicates that the function only takes zero arguments. In this case (and many others), it really doesn't matter too much.

If you want to be strict though, it's probably best to define the void parameter. Of course, the main function can also be defined as int main(int argc, const char* argv[]) - which is perfectly valid, but often unnecessary if you don't care about arguments.

Solution 2:

From the C99 standard:

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.

When main is defined without parameters, will argc and argv still be present on the stack?

Solution 3:

These prototypes of main() are both non-standard.

Precision on that question can be found on the comp.lang.c faq : http://c-faq.com/decl/main.html

EDIT: changed "wrong" to "non-standard" as the norm allows implementation-defined prototypes.

Solution 4:

There is no difference but usually main should return int. Some compilers will give you a warning (at least the GNU compiler - gcc):

$ cat x.c
void main(void){}

$ gcc x.c
x.c: In function `main':
x.c:1: warning: return type of 'main' is not `int'

As mentioned the prototype of main is (according to standard):

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