Hans Schneider said:
Billy said:
Hi, in C90 is "int main()" valid, the same as "int main(void)" and "int
main(int argc, char *argv[])"?
AFAIK in C99 only "int main(void)" and "int main(int argc, char *argv[])
- and the **argv syntax" are the only valid ones.
In reality, "void main()" is also valid.
That's what I thought always, but I'm not anymore so sure. According to
a recent thread...
* H. Schildt (book writer and ISOC member)
- writes that you are free to use void main()
* Richard Heathfield (book writer)
- says that void main() is false
* Chris Hills (ISOC member)
- says that void main() is valid C
* Jack Klein (writer of C library and inventor of Klein Bottle)
- says that void main() is not valid C code
[...]
Herbert Schildt is notorious for his dangerously incorrect books.
See, for example, <
http://www.lysator.liu.se/c/schildt.html> and
<
http://www.seebs.net/c/c_tcr.html>.
Here's the truth.
There are two kinds of conforming C implementations, hosted and
freestanding. You're not likely to run into a freestanding
implementation unless you work on embedded systems (though it's been
argued that some MS Windows C implementations are really
freestanding).
For a hosted implementation, the main function may have this form:
int main(void) { /* ... */ }
or this form:
int main(int argc, char *argv[]) { /* ... */ }
or equivalent. The "or equivalent" allows for things like using a
typedef for int rather than int, or using "char **argv" rather than
"char *argv[]", or using different names for argc and argv.
If you define main in any other way, such as
void main(void) { /* ... */ }
then the behavior of your program is undefined. It's not "illegal",
in the sense that the compiler isn't required to complain, but it's
not required to work, and the compiler *could* reject it outright.
*Except that*, in both C90 and C99, implementations are permitted to
provide extensions, as long as they don't break anything. (That's a
somewhat imprecise summary; see the standard for the exact wording.)
Such extensions must be documented. So if your compiler's
documentation says that "void main(void)" is allowed, and specifies
what it does, then a program that uses "void main(void)" has well
defined behavior *for that implementation*. But if you try to compile
and run that some program on another implementation, it might fail to
work, in ways ranging from being rejected outright by the compiler to
misbehaving in subtle ways during execution.
If you write "int main(void)", you *know* that it will work under any
conforming hosted implementation. Writing "void main(void)" gains you
absolutely nothing; it just makes your program less portable.
Remember that those implementations that allow "void main(void)" are
still required to support "int main(void)".
To summarize, "void main(void)" isn't actually illegal, but it may or
may not work; "int main(void)" will always work. (The rules are
different for freestanding implementations.)