1.1 — Statements and the main function
Statements#
A statement is one step in your program. It is like one sentence.
std::cout << "Hi!\n"; // one statementint age = 12; // another statementMost 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.
#include <iostream> int main(){ std::cout << "Step 1\n"; std::cout << "Step 2\n"; std::cout << "Step 3\n"; return 0;}Step 1Step 2Step 3The 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;endsmainand says "everything went fine".
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:
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.
Indent everything inside { } by 4 spaces. It makes it easy to see what belongs where.
Tip: press ← / → to move between lessons, / to search.