Question

In a book (don't remember which one) they used:

void main(void)

In school I learned:

int main(void)

Is there any case when void main(void) is actually correct? Or at least not explicitly wrong?

EDIT: According to the proposed answers since C99 it is not correct. What about earlier versions? Is it explicitly wrong or just nothing said about it? Why do C compiler not complain about it?

Was it helpful?

Solution 3

void main(void) is allowed by some(all?) C compilers. However, it should not be used anyway. Because at least since C99 is it not allowed. However, I did not find a C compiler which complains about it.

E.g. void.c:

#include <stdio.h>
void main(void)
{
   printf("hello world");
}

gcc void.c

Compiles. Also check http://www.compileonline.com/compile_c_online.php

So in conclusion (even though I do not find references): In earliest C versions void main(void) was probably not forbidden.

However: Without specifying a return value, you just do not now what your program returns. So, standard or not, correct or false, do not use it, because it makes your program non-deterministic.

OTHER TIPS

Never, ever use void main(void). It is not standard.

Always use one of

int main(void);

int main();

int main(int argc, char **argv);

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

And the best use of said book is to use it to light your first fire for the winter.

Per the C standard

C99 §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;10 or in some other implementation-defined manner.

10) Thus, int can be replaced by a typedef name defined as int, or the type of argv can be written as char **argv, and so on.

The closing clause grants implementations their own vices, which is to say, if a program does not follow this, it is no longer standard-compliant and instead reliant on the implementation for compatibility. If you want your main() to work everywhere, follow one of these and you'll be ok.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top