Your First C++ Program, Explained
Here is the program from the last lesson again. This time, let's look at each line.
#include <iostream>
using namespace std;
int main() {
cout << "Hello, C++!" << endl;
return 0;
}
Output:
Hello, C++!
#include <iostream> adds the part of the C++ library that reads and prints text. The name means "input/output stream". Without this line, the compiler does not know what cout is.
using namespace std; saves you some typing. Everything in the C++ standard library has the prefix std::, so the full name of cout is std::cout. This line lets you write just cout. Every program in this course uses both of these lines.
int main() { ... } is the main function. Every C++ program has exactly one. When the program runs, the computer starts at the first line inside its curly braces { } and goes down, line by line.
cout << "Hello, C++!" << endl; prints. cout is the screen output, and << sends the value on its right to it. endl means "end of line": the next print starts on a new line.
return 0; ends main. The 0 tells the computer that the program finished without problems.
Semicolons
Each statement inside main ends with a semicolon ;. If you forget one, the program does not compile:
#include <iostream>
using namespace std;
int main() {
cout << "Hello, C++!" << endl
return 0;
}
Output:
main.cpp: In function ‘int main()’:
main.cpp:5:34: error: expected ‘;’ before ‘return’
5 | cout << "Hello, C++!" << endl
| ^
| ;
Read the error from the left. main.cpp:5:34 means file main.cpp, line 5, character 34. That is the end of the cout line. The message says that a ; is missing before return, and the last line even shows the ; where it should go. C++ errors look long, but the first lines usually tell you what to fix.
Printing more than one line
You can chain several values with <<, and you can mix text and numbers. To end a line, you can also write "\n" instead of endl. Both start a new line, and this course mostly uses "\n".
#include <iostream>
using namespace std;
int main() {
cout << "Line one" << "\n";
cout << "Line " << 2 << "\n";
return 0;
}
Output:
Line one
Line 2
Shorter examples from now on
Every program needs the lines around main. To keep the lessons short, from now on some examples show only the lines that go inside main. When you see such an example, imagine it inside int main() { ... }, with the #include and using lines on top. The exercises always show the whole program.
Now finish a program that prints two lines.