1.1 — Statements and the main function

📘 Chapter 1⏱ about 2 min read✍️ Beginner friendly
Read one box at a time. No rush.

Statements#

A statement is one step in your program. It is like one sentence.

C++
std::cout << "Hi!\n";   // one statementint age = 12;           // another statement

Most statements end with a semicolon ;.

The main function#

Statements live inside functions. A function is a named group of statements.

Every C++ program must have exactly one function called main. When your program starts, it runs main, top to bottom.

C++▶ Run
#include <iostream> int main(){    std::cout << "Step 1\n";    std::cout << "Step 2\n";    std::cout << "Step 3\n";    return 0;}
Output
Step 1Step 2Step 3
Key idea

The program starts at the top of main and runs one statement at a time, in order.

The shape of a program#

  • #include <...> lines go at the top. They load tools.
  • int main() starts the main function.
  • { opens the body. } closes it.
  • return 0; ends main and says "everything went fine".
Syntax

The grammar rules of a language. A syntax error means you broke a rule, like forgetting a ; or a }. The compiler will tell you.

Spaces and new lines#

C++ mostly ignores extra spaces and blank lines. These two do the same thing:

C++
std::cout << "Hello\n";std::cout    <<    "Hello\n"   ;

We use spaces and indenting (moving code to the right) to make code easy for people to read.

Good habit

Indent everything inside { } by 4 spaces. It makes it easy to see what belongs where.

Finished reading? Tick it off. Your progress is saved in this browser.

Tip: press ← / → to move between lessons, / to search.