Print Page | Close Window

query

Printed From: One Stop GATE
Category: GATE Technical Discussions
Forum Name: GATE CS
Forum Discription: General Technical Discussions, Queries, doubts etc. for GATE in CS.
URL: http://forum.onestopgate.com/forum_posts.asp?TID=217
Printed Date: 19Feb2025 at 4:16pm


Topic: query
Posted By: Pallavi
Subject: query
Date Posted: 03Feb2007 at 3:10pm
why is int main() used when void main() is good enough?



Replies:
Posted By: Preeti
Date Posted: 03Feb2007 at 4:24pm
Historically, when C was first specified, there was no void main(). main() by default was supposed to return an integer vaule and so is if we declare int main(). Actually at that time there were two diclarations, int main() and int main(int argc, char **argv).

Now suppose you start writing a program with main() or int main(). If the program does not have an exit() code in between it must return a value, otherwise the compiler issues a warning. Now as I said the ANSI/ISO C Standard specifies that main() should be declared as int. So when runtime environment assumes that main returns an int, declaring main with any other return type, including void, invites trouble. The compiler might compile such a program, since the ANSI Standard doesn't require it to fail, but the behavior of such a program is, in the Standard's parlance, "undefined". That's why GCC returns an error in case we use void main().

In C++, the situation is good. void main() use is explicitely prohibited there and in case you forget to return, the compiler adds a return 0 itself!

Void main() in C is actually introduced to bypass the "complexity" to return.



Print Page | Close Window