Difference between void main() and main()

lifesamd

Honorable
Jan 14, 2013
9
0
10,510
Hey,
First of all, am a noob in programming.. Am just starting to learn.. Now,
I use Dennis Ritchie's book "the c programming language" as reference for learning the C language... The examples he gave for running the hello world program and many many others all start with main() and that works fine when i use Visual studio to compile the program.. But when I use a compiler like Turbo C++, it says that the function should return a value.. So, I now have to add a void in front of main. And this is also taught in my college, that is to use void main().
My questions are:
1. Why does the program run in VS but not in TurboC++ when i use main() instead of void main()?
2. What should I use to compile? Which one is a better option?
3. If Dennis Ritchie himself wrote the code that way, why doesn't it work? And why are we taught so many things in college which differ from what the book states? Like in college we are taught to use getch() instead of getchar().

I am just confused about what's right and what's wrong!!!
 
Solution
Are you returning 0 at the end of the main() program? It sounds like you're not. The reason why it doesn't give that error when you're using the void main() is because a void function doesn't require a return value.

Type "return 0;" at the end of the main() program and it'll compile just fine.

Edit: My guess is that the first compiler detects a lack of return value and assumes it for you if it's not there. The second however requires a bit more specificity, asking you to explicitly type it in. The default return value for a function is 0.

Ijack

Distinguished
If you don't specify a return type then the compiler assumes it is int. I'm not sure why your program compiles in VS; it should at least give a warning that you aren't returning a value.

The moral is that you really ought to specify a return type for all functions, even if it is void. C has evolved a lot since Ritchie's book, so don't stick to everything he does religiously. Listen to what you are taught. Study all the compiler warnings and try to ensure that you deal with the causes of all of them.
 

calmstateofmind

Distinguished
Jul 2, 2009
292
0
19,010
Are you returning 0 at the end of the main() program? It sounds like you're not. The reason why it doesn't give that error when you're using the void main() is because a void function doesn't require a return value.

Type "return 0;" at the end of the main() program and it'll compile just fine.

Edit: My guess is that the first compiler detects a lack of return value and assumes it for you if it's not there. The second however requires a bit more specificity, asking you to explicitly type it in. The default return value for a function is 0.
 
Solution