Every C++ program starts running from main(). Header files bring in library code, and using namespace std; lets us write cout instead of std::cout.
#include <iostream> // header for input / output
using namespace std; // use names from std without std::
int main() { // execution starts here
int age;
cout << "Enter age: ";
cin >> age; // input
cout << "Age is " << age << endl; // output
return 0; // 0 = program ended successfully
}
- #include is a preprocessor directive; it copies the header in before compiling.
- cin uses
>>(extraction), cout uses<<(insertion). endladds a new line and flushes the buffer;"\n"only adds a new line (faster).
Q & A
-
What is the difference between C and C++?C is procedural. C++ adds object-oriented programming (classes, inheritance, polymorphism), references, function overloading, templates, exceptions and the STL.
-
Why does main() return int?The return value goes to the operating system. 0 means success, any other value means an error.