Mail Archives: djgpp/1996/07/08/01:23:41
Reply to message 8912282 from LAURIN AT CYBERH on 07/07/96 3:54PM
>i am using an online tutorial and it suddenly went from using main to void
>main without telling me why. could someone please explain the difference?
If you can, you may want to look through the mailing list traffic for the
last couple of days; there were some messages there that explored
some of the intricacies of what happens when you declare main to return
void.
Basically, however, it is very bad programming to declare void main()
instead of int main(). This is because main is supposed to return int, and
the potential exists to really mess up other programs if it doesn't return
what it is supposed to. Many C tutorials and books gloss over this fact,
because it is technically a minor shortcut. If you don't declare main with
a return value, then (as far as the compiler is concerned) you can omit
the 'return 0;' line at the end of the function. Since most programs don't
return anything significant to the operating system (or if they do, they do
it with exit()), most programmers can get away with this most of the time.
For an example of the times they _can't_ get away with it, see my post of
7/6 titled "Re: Does DJGPP conform to ANSI C?".
To summarize, there are only two absolutely correct ways to declare main():
int main( void )
int main( int argc, char **argv )
Use the latter if you need to work with command-line arguments, and the
former if you don't. In any case, the last statement of main() should be
'return 0;', to indicate to the operating system and any programs that
run your program that it executed successfully. Unfortunately, many C
texts fail to stress these correct definitions, and as a result there are a
lot of misguided programmers out there. This applies as well to your
online tutorial.
BTW, just using 'main()' as your definition is not very good either. While it
is technically correct (an unstated return value defaults to int and an empty
argument list defaults to void), you are relying on the _compiler_ to choose
the correct defaults. When you state them explicitly, you leave no room for
ambiguity.
John
- Raw text -