Explain it simply
Explain it simply
C++ code is a list of instructions written in a strict format, a little like a recipe for a cook who follows every word literally. Each instruction is a statement, and it ends with a semicolon the way a sentence ends with a full stop. Related statements are grouped inside curly braces { }, and the group named main is where the cook starts reading.
Above main you list the libraries you need with #include, much like listing the kitchen tools before the steps. If a tool is missing or a full stop is forgotten, the compiler stops before anything runs and tells you the line.
Problem → Why → Solution
The problem: one missing character, a confusing error
A beginner writes a two-line program and forgets one semicolon. The compiler does not say "add a semicolon on line 4". It points at the end of line 4 and reports that it expected ';' before 'return', a word on the next line. Other small slips, such as a missing quote or an extra brace, produce messages that seem to point somewhere else entirely.
#include <iostream>
int main() {
std::cout << "Hello World!"
return 0;
}
// g++ -std=c++20 hello.cpp -o hello
// hello.cpp:4:32: error: expected ';' before 'return'Why does the error mention the next line?
The compiler reads your code as a stream of tokens, and line breaks mean nothing to it. A statement ends only where a semicolon appears, so std::cout << "Hello World!" return 0 reads as one long broken statement, and the problem is detected only when the token return arrives. That is why the reported position is often just after the real mistake: when an error points at a line that looks fine, check the end of the line above it first.
Core concept: the parts of a program
1. The #include directive
#include <iostream> is a preprocessor directive, not a statement, so it takes no semicolon. It pastes in the declarations of std::cout. Angle brackets < > are used for standard library headers.
2. The main function
Every program has exactly one main, and the operating system calls it. int is its return type, the exit status; void main() is not valid C++. main alone has a special rule: reaching its closing brace without a return statement counts as return 0.
3. Statements and blocks
Each statement ends with ;, and braces group statements into a block. The compiler ignores spaces and indentation, but people depend on them, so indent the inside of every block, for example by four spaces.
4. std:: and namespaces
The standard library keeps its names in the namespace std, so cout's full name is std::cout; :: is the scope resolution operator. using namespace std; pulls every std name into your code, which is convenient in tiny programs but can clash with your own names and must never appear in a header file. This course writes std:: in full.
5. Comments
// starts a comment that runs to the end of the line, and /* ... */ can span several lines. The compiler throws comments away, so use them to explain why the code does something rather than repeating what it does.
Printing uses the << operator: std::cout << value sends a value to standard output, and one statement can chain several <<. A line ends only when you print '\n' or std::endl. For text that mixes words and numbers, std::format from <format> (C++20) builds a complete string from a pattern with {} placeholders, which is often easier to read than a long chain of <<.
- #include pastes in library names
- Tokens are read; line breaks ignored
- Each ; closes one statement
- main's block runs top to bottom
When an error points at a line that looks fine, check the end of the line above.
General pattern: program structure
#include <header> // directives: no semicolon
// single-line comment
/* multi-line
comment */
int main() {
statement; // every statement ends with ;
{
statement; // braces group statements into a block
}
return 0;
}Directives sit at the top of the file and need no semicolon. Inside main's braces, statements run in order, and a block can contain further blocks.
Example: three lines, three ways to print
This program shows three ways to produce output: std::cout with '\n', std::cout with std::endl, and std::format. The comments label each part of the program. Predict the three output lines before you run it.
#include <format> // std::format (C++20)
#include <iostream> // std::cout, std::endl
/* A first program: two plain lines of output,
then one line built with std::format. */
int main() {
std::cout << "Hello World!\n"; // '\n' ends the line
std::cout << "C++ is ready." << std::endl; // endl ends it and flushes
std::cout << std::format("{} + {} = {}\n", 2, 3, 2 + 3);
return 0; // 0 tells the system: success
}Code breakdown
- Lines 1-2
#include <format> // std::format (C++20)Each header brings in one part of the library: <format> provides std::format and <iostream> provides std::cout. Their order does not matter, but alphabetical order makes them easy to scan.
- Line 6
int main() {Execution starts here. The { opens main's block, which the } on line 12 closes.
- Line 7
std::cout << "Hello World!\n";The \n inside the quotes is a single newline character, so the next output starts on a new line. The semicolon ends the statement.
- Line 8
std::cout << "C++ is ready." << std::endl;std::endl also ends the line, but it additionally flushes the output buffer, forcing waiting text out immediately. For one line you cannot see the difference; in a loop printing thousands of lines it slows the program down.
- Line 10
std::format("{} + {} = {}\n", 2, 3, 2 + 3)Builds a string by replacing each {} with the following arguments in order: 2, 3 and the result of 2 + 3, which is 5. std::cout then prints the finished string.
- Line 11
return 0; // 0 tells the system: successReturning 0 from main tells the shell the program succeeded. For main specifically, leaving this line out gives the same result.
Hello World!
C++ is ready.
2 + 3 = 5Writing std:: or using a using-declaration
std holds thousands of names: count, size, min, max, distance and many more. using namespace std; drops all of them into your code. In our tests with GCC 16, a program with #include <algorithm> and using namespace std; that declares a global variable named count fails with "reference to 'count' is ambiguous", because the compiler cannot tell your count from std::count. Worse, this can appear suddenly, just because someone added an include.
The middle ground is a using-declaration: using std::cout; brings in that one name and leaves the rest inside std. It is common in .cpp files, while header files are safest with std:: written in full.
#include <iostream>
#include <string>
using std::cout; // bring in just this one name
using std::string;
int main() {
string city = "Yangon";
cout << "Hello from " << city << '\n';
std::cout << "The full name std::cout still works.\n";
return 0;
}Shaping output with std::format
Inside the {} of std::format you can add a format spec: {:.2f} gives two decimal places, {:>6} right-aligns in six characters, {:<6} left-aligns and {:^6} centers. Numbers such as {1} pick arguments out of order, and {{ and }} print real braces. The format string is checked at compile time, so a missing argument is a long compile error rather than a surprise at runtime.
#include <format>
#include <iostream>
int main() {
std::cout << std::format("{} scored {} points\n", "Aye", 87);
std::cout << std::format("Average: {:.2f}\n", 82.756);
std::cout << std::format("[{:>6}] [{:<6}] [{:^6}]\n", 42, 42, 42);
std::cout << std::format("{1} before {0}\n", "second", "first");
std::cout << std::format("Literal braces: {{ and }}\n");
return 0;
}Aye scored 87 points
Average: 82.76
[ 42] [42 ] [ 42 ]
first before second
Literal braces: { and }std::println in C++23
C++23 adds std::print and std::println in the <print> header, which print formatted text directly: std::println("{} + {} = {}", 2, 3, 5);. Not every toolchain supports them yet, so this course uses std::cout with std::format; the {} placeholders work the same way.
In real projects
Syntax conventions in real codebases
The compiler ignores whitespace, but teams do not. Most projects fix brace placement, indentation width and maximum line length in a style guide, and a tool such as clang-format reformats the code automatically on every save. Code reviews can then focus on logic instead of spacing. A single .clang-format file at the project root makes every team member's editor follow the same rules.
Big style guides turn this lesson's advice into rules: the Google C++ Style Guide forbids using-directives such as using namespace std, and code that writes a lot of log output prefers '\n' to std::endl because every flush can cost a system call. Comments can work harder too: tools such as Doxygen turn comments that start with /// into a documentation website.
Common mistakes
Common syntax mistakes
1. Curly "smart" quotes copied from a document
Word processors and chat apps often turn " into “ and ”. Paste that code into a .cpp file and GCC 16 reports "extended character “ is not valid in an identifier". Retype the quotes in your code editor.
2. Semicolons where they do not belong
#include <iostream>; gives the warning "extra tokens at end of '#include' directive", and int main(); { gives the error "expected unqualified-id before '{' token": the ; ends main as a declaration without a body, so the block after it belongs to nothing. Directives and function headers take no semicolon.
3. A missing closing brace
Leave a { unclosed and GCC only notices at the end of the file: "expected '}' at end of input", with a note pointing to the { it tried to match. Type the closing brace as soon as you open a block, then fill it in, and keep indentation consistent so a missing brace stands out.
4. Putting using namespace std; in a header
using namespace std; in a header spreads into every file that includes it, causing clashes like the count ambiguity above in files you never touched. Write std:: in full in headers.
Mini challenge
Mini challenge: a study plan table
Use std::format to print a small table of three lessons and a total, with the columns lined up.
- Use only std:: names (no using namespace std;)
- After a title line, print three rows: the lesson name left-aligned in 12 characters and the minutes right-aligned in 4
- The program computes the number on the Total row
- Include one // comment and one /* */ comment
#include <format>
#include <iostream>
// TODO: a /* */ comment that says what the program prints
int main() {
// TODO: print the title "Study plan"
// TODO: three rows: name left-aligned in 12, minutes right-aligned in 4
// hint: std::format("{:<12}{:>4}\n", name, minutes)
// TODO: a Total row whose number the program computes
return 0;
}Expected: The output should be: Study plan Intro 15 Setup 20 Syntax 25 Total 60
Show hint
{:<12} left-aligns a value and pads it with spaces to 12 characters; {:>4} right-aligns to 4. Using the same format string on every row lines the columns up.
Show solution
#include <format>
#include <iostream>
/* Prints a small study plan.
Every row uses the same format string, so the columns line up. */
int main() {
std::cout << "Study plan\n";
std::cout << std::format("{:<12}{:>4}\n", "Intro", 15);
std::cout << std::format("{:<12}{:>4}\n", "Setup", 20);
std::cout << std::format("{:<12}{:>4}\n", "Syntax", 25);
// the program does the adding, not us
std::cout << std::format("{:<12}{:>4}\n", "Total", 15 + 20 + 25);
return 0;
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- #include directives go at the top with no semicolon, and the program starts in int main().
- Every statement ends with ;, braces define blocks, and the compiler ignores line breaks.
- '\n' ends a line, std::endl also flushes, and std::format builds text from {} placeholders.
- Standard library names live in std: write std:: in full or import single names with using std::cout;.
The Current ISO C++ Standard (C++23) — Standard C++ Foundation