[Courses] Absolute Beginning C: void?

Akkana Peck akkana at shallowsky.com
Mon Feb 6 05:19:45 UTC 2012


techno curmudgeon writes:
> In looking around (extracurricular reading?  I never even did that in
> university!) a lot of the 'hello world' examples start with 'void' in
> front of main().
[ ... ]
> I don't want to get too off track here.  Since hello world worked, a
> void keyword is not required (right?).  And since it didn't generate a
> warning, it's not even bad form not to have one, right?
> 
> I guess that's my question.  While not needed, is it good practice to
> use the 'void' keyword?

Good question -- and you've already come up with a good answer.
Here's why.

In C, if you don't specify the type of a function, the compiler will
assume it returns an int (integer). And in fact, the function main()
can return an integer: it's the exit code you want to pass back to
the shell when you quit. That might matter if you were running your
program from inside a shell script.

For little programs like this, there's no need to bother with
returning error codes, so you're going to pretend that main() doesn't
return anything, and so it actually is good coding practice to say

void main()

One reason it's good practice is that you can set the compiler to
tell you about warnings -- things that might be errors in your code
but they're not bad enough to keep you from compiling it. Most good
C programmers include flags like -Wall (show all warnings) when they
compile C, and if you try that on your program without declaring
main() to be void, you'll get a nice juicy warning about it:

$ cc -o foo -Wall foo.c
foo.c:3:1: warning: return type defaults to ‘int’ [-Wreturn-type]
foo.c: In function ‘main’:
foo.c:5:1: warning: control reaches end of non-void function [-Wreturn-type]

What it's saying in plainer English is "Hey, dummy, you said main was
supposed to return an int, but you never actually return one anywhere!"

So for the purposes of a beginning class, there's no reason at all
to worry about it. But if you want to get into good habits from the
very beginning, you can either use "void main()", or else say
"int main()" and then end your program with a "return 0;"
And if you leave off the "int", C will assume it, but it's good
practice to include it if you're going to be returning something.

	...Akkana


More information about the Courses mailing list