C++ Syntax

Every C++ program follows a set of rules called syntax. On this page we break down the small Hello World program line by line so you understand what each part does and why it is there.

Breaking down a program

Let's revisit the program from the previous page. Each line has a specific job, and once you know what they do, you will recognize them in almost every C++ program you write.

The full program

#include <iostream>
using namespace std;

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

Line by line

CodeMeaning
#include <iostream>Loads the input/output library so we can print and read text
using namespace std;Lets us write cout instead of std::cout
int main()The main function where the program begins running
cout << ...Sends text to the screen
return 0;Tells the system the program finished successfully

Semicolons and braces

  • Most C++ statements end with a semicolon ( ; ). Forgetting it is one of the most common beginner errors.
  • Curly braces { } group a block of code together, such as the body of the main function.
  • C++ is case sensitive, so main and Main are treated as two different names.

You can write more than one statement inside main. Each statement runs in order from top to bottom.

Two statements in a row

#include <iostream>
using namespace std;

int main() {
  cout << "Learning C++";
  cout << " is fun!";
  return 0;
}
Note: Whitespace (spaces, tabs, and blank lines) is mostly ignored by the compiler. Use it generously to keep your code readable, but never forget the semicolons.

Exercise: C++ Syntax

What must every executable C++ program contain?