C++ Get Started
A C++ program is written as text, then a compiler turns it into a program the computer can run. On your own computer you would install a compiler such as GCC (g++), Clang or Visual C++. In this tutorial the online editor compiles and runs your code for you.
Your first program
#include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl;
std::cout << "Welcome to C++." << '\n';
return 0;
}Hello, World! Welcome to C++.
#include <iostream>brings in the input and output part of the standard library, which declaresstd::cout.int main()is where the program starts. Every program has exactly onemain.std::coutis the console output. The output operator<<sends the value on its right to it; several can follow each other.std::endlends the line (and flushes the output); the newline character'\n'also ends the line.return 0;tells the system the program finished well. Inmainyou may leave it out: C++ then returns 0 for you.- Every statement ends with a semicolon.
Compiling in the terminal
When you press Run, the editor types:
g++ -Wall main.cpp -o main && ./main
g++ compiles main.cpp into a program called main; -Wall asks for warnings about suspicious code. ./main runs it, but only if compiling worked (&&).
using namespace std
Everything in the standard library lives in the namespace std, which is why the names start with std::. Many beginner examples add using namespace std; so they can write cout and endl alone:
#include <iostream>
using namespace std;
int main() {
cout << "Shorter to type" << endl;
return 0;
}Shorter to type
It is fine in small programs like these. In larger programs and in header files, professionals write std:: explicitly, because a using line can cause name clashes. This tutorial uses both styles.
Practice exercises
- Print your name and your city on two lines.
- Print the same two lines with a single
coutstatement. - Remove
std::beforecout(withoutusing namespace std;) and read the error and the hint.