Sunday, 31 March 2013

Simple c++ program

#include<iostream>
using namespace std;

int main()
 {
  cout << "Hello World";
  return 0;
}


Here are a few observations about this program:
  • This is a Standard ISO C++ program using the standard library. Standard library facilities are declared in namespace std in headers without a .h suffix.
  • If you want to compile this on a Windows machine, you need to compile it as a "console application". Remember to give your source file the .cpp suffix or the compiler might think that it is C (not C++) source.
  • Yes, main() returns an int.

Can I write "void main()"?

The definition
 void main() { /* ... */ }
is not and never has been C++, nor has it even been C.

A conforming implementation accepts
 int main() { /* ... */ }
and
 int main(int argc, char* argv[]) { /* ... */ }
A conforming implementation may provide more versions of main(), but they must all have return type int. The int returned by main() is a way for a program to return a value to "the system" that invokes it. On systems that doesn't provide such a facility the return value is ignored, but that doesn't make "void main()" legal C++ or legal C. Even if your compiler accepts "void main()" avoid it, or risk being considered ignorant by C and C++ programmers.

In C++, main() need not contain an explicit return statement. In that case, the value returned is 0, meaning successful execution. For example:
 #include<iostream>

 int main()
 {
  std::cout << "This program returns the integer value 0\n";
 }
Note also that neither ISO C++ nor C99 allows you to leave the type out of a declaration. That is, in contrast to C89 and ARM C++ ,"int" is not assumed where a type is missing in a declaration. Consequently:
 #include<iostream>

 main() { /* ... */ }
is an error because the return type of main() is missing.

 Ref: http://www.stroustrup.com/bs_faq2.html#void-main

2 comments:

  1. Thanks for the info about void main() and int main() ma'am :)

    ReplyDelete