Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 171 ยท Getting Started

C++ Syntax

Learn the core rules of C++ syntax: main, statements, semicolons, blocks, #include, namespaces, std::, using declarations and reading compiler errors.

Every language has grammar rules, and C++ is stricter than most. The compiler reads your code exactly as written: a missing semicolon, a wrong capital letter or a stray brace stops the build. The good news is that the core rules are few, and once you know them, you can read the structure of almost any C++ program.

In this lesson you'll take a short program apart piece by piece: the main function, statements, blocks, #include lines, namespaces and the famous std:: prefix. You'll also see why many experienced developers avoid using namespace std;, and how to read the error messages the compiler gives you when something goes wrong.

The shape of a C++ program

Here's a small but complete program. Run it, then read the walkthrough below:

C++ Anatomy of a program

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

From top to bottom:

  1. Include lines (#include <print>, #include <string>) make standard library features available.
  2. The main function (int main() { ... }) is where the program starts.
  3. Statements inside main do the work: they create variables, print text and make decisions.
  4. Blocks in curly braces group statements together, for the whole function and for the if.
  5. return 0; ends main and reports success to the operating system. It's optional in main, but common.

Let's look at each rule.

The main function

Every C++ program needs exactly one function named main. The operating system calls it when your program starts, and the program ends when main finishes. The standard allows two forms:

C++
int main() { /* ... */ }
int main(int argc, char* argv[]) { /* ... */ }

The second form receives the command-line arguments the program was started with; you'll use it much later. main must return int. Writing void main() is an old mistake that some compilers accept, but it isn't valid C++.

Statements and semicolons

A statement is one complete instruction. Most statements end with a semicolon:

C++
int apples = 3;                 // declares a variable
apples = apples + 2;            // changes it
std::println("{}", apples);     // calls a function

The semicolon is not a separator between lines; it's part of the statement, like a period at the end of a sentence. Lines don't matter to the compiler at all. You could put three statements on one line, or spread one statement across five lines. Whitespace (spaces, tabs and line breaks) only separates words, so this ugly program is perfectly legal:

C++ Whitespace doesn't matter to the compiler

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

It prints 7 pieces of fruit. Of course, people need to read code too. This course uses one statement per line and 4-space indentation, which is the most common style. The exception is #include and other preprocessor directives: they must each be on their own line, and they don't end with a semicolon.

Some constructs don't end with a semicolon either, because they end with a block instead: function definitions (int main() { ... }), if, for and while. Class and struct definitions are a famous exception: they need a semicolon after the closing brace (struct Point { int x; int y; };), and forgetting it produces confusing errors.

Blocks and indentation

A block (also called a compound statement) is a group of statements in curly braces { }. Blocks appear as function bodies and as the bodies of if, for and while. They can also stand alone to create a small region where variables live:

C++ Blocks group statements

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

A variable declared inside a block can only be used inside that block. Try adding std::println("{}", bonus); just before Done. and the compiler will say that bonus was not declared in this scope. That idea, called scope, comes back in Variables and gets its own lesson later.

Indentation has no meaning to the compiler, unlike in Python. It exists only to show humans which statements belong to which block. Indent consistently anyway: misleading indentation hides bugs, and GCC even warns about some cases (-Wmisleading-indentation).

#include and headers

C++ itself has very few built-in facilities. Printing, strings, lists, math functions and files all live in the standard library, split into headers. You include the headers you need at the top of the file:

Header Gives you
<print> std::print, std::println (C++23)
<iostream> std::cout, std::cin, std::cerr
<string> std::string
<vector> std::vector
<cmath> std::sqrt, std::pow and other math
<algorithm> std::sort, std::find and many more

Standard headers go in angle brackets and have no .h extension. Your own headers use quotes, like #include "shapes.h", which you'll learn in Header Files and Multiple Source Files.

Warning: Sometimes code compiles even though you forgot an include, because another header happened to include it for you. Don't rely on that: it can break on a different compiler. Include every header whose features you use. You may also see #include <bits/stdc++.h> in competitive programming code. It's a GCC-only shortcut that includes everything, slows compilation and isn't standard C++, so avoid it in real projects.

Namespaces and std::

Large programs use thousands of names. Two libraries might both define a function called log or a type called Vector. C++ prevents clashes with namespaces: named containers for related names. Everything in the standard library lives in the namespace std, which is why you write std::println and std::string.

The :: is the scope resolution operator. Read std::println as "the println that belongs to std". You can create your own namespaces too:

C++ Your own namespace

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Both namespaces contain a function named to_meters, yet there's no conflict, because the full names are metric::to_meters and nautical::to_meters. The output is 5 km = 5000 m and 5 nautical miles = 9260 m. The Namespaces lesson covers nesting, anonymous namespaces and more.

using declarations and using namespace

Typing std:: everywhere can feel repetitive, so C++ offers two shortcuts.

A using declaration brings in one specific name:

C++
#include <print>
#include <string>

using std::println;
using std::string;

int main() {
    string name = "Ada";
    println("Hello, {}!", name);
}

A using directive brings in every name from a namespace at once:

C++
#include <iostream>
using namespace std;

int main() {
    cout << "Hello!\n";
}

You'll see using namespace std; in countless tutorials and textbooks. It's convenient in tiny programs, but it dumps hundreds of standard names (count, distance, size, min, data, begin and many more) into your code, where they can collide with your own names. Run this example; it fails on purpose:

C++ using namespace std causes a clash (on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The compiler reports error: reference to 'count' is ambiguous: it can't tell whether you mean your variable count or the algorithm std::count. Delete the using namespace std; line and write std::cout, and the program works. Worse, a clash like this can appear years later when a new C++ version adds a new name to std.

The rules professionals follow:

  • Never put using namespace std; (or any using directive) in a header file. Every file that includes the header inherits it, and you can't undo it.
  • Prefer writing std:: explicitly. It's five characters, and it tells readers exactly where a name comes from.
  • If a name is used constantly, a targeted using std::println; inside a .cpp file or a function is fine.

This course writes std:: everywhere, which is also what you'll see in most professional codebases.

C++ is case-sensitive

Uppercase and lowercase letters are different characters to the compiler. total, Total and TOTAL are three different names, and Main is not the same as main. All C++ keywords (int, return, if) and nearly all standard library names (std::println, std::string) are lowercase:

C++ Wrong capital letter (on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

GCC answers with error: 'Println' is not a member of 'std'; did you mean 'println'?. Fix the capital P and the program runs.

Reading compiler errors

Compiler errors are your most useful feedback, so learn to read them calmly. A typical GCC error looks like this:

TEXT
main.cpp: In function 'int main()':
main.cpp:6:34: error: 'Totl' was not declared in this scope; did you mean 'Total'?
    6 |     std::println("{} {}", total, Totl);
      |                                  ^~~~
      |                                  Total
  • main.cpp:6:34 is the file, line and column of the problem.
  • error: is followed by the description. Lines starting with warning: are warnings, and lines with note: add extra details to the error above them.
  • The code line with ^~~~ under it shows exactly where the compiler got confused, and GCC often suggests a fix.

A few habits make errors much less painful:

  1. Fix the first error first. One mistake can confuse the compiler and cause a cascade of follow-up errors. Fixing the first often makes the rest disappear.
  2. Look one line up. For a missing semicolon or brace, the compiler often notices only at the start of the next line, so the real mistake is just before the reported location.
  3. Skim long errors. Errors involving the standard library can be dozens of lines of notes about library internals, like the count example above. Find the first line that mentions main.cpp and the word error; that's usually the one that matters.
  4. Change one thing, then rebuild. Small steps make it obvious which fix worked.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does this line print? std::println("{}", 2 + 3 * 4);

    Whitespace between tokens doesn't matter, and multiplication happens before addition, so the result is 2 + 12 = 14.
  2. 2. Which of these lines does NOT end with a semicolon in correct C++?

    Preprocessor directives like #include are handled before compilation and are not statements, so they never take a semicolon.
  3. 3. Why is using namespace std; in a header file considered bad practice?

    A using directive in a header leaks into every file that includes it. Names like count or size can then collide with user code.
  4. 4. A program declares int total = 1; and later prints Total. What happens?

    C++ is case-sensitive, so Total is a different, undeclared name. GCC reports that it was not declared in this scope.
  5. 5. The compiler reports 12 errors after you edit one line. What should you do first?

    Later errors are often side effects of the first one. Fixing it and rebuilding usually clears many of the others.

Summary

  • Every program has exactly one int main(), where execution begins.
  • Statements end with a semicolon; whitespace and line breaks don't matter to the compiler, but consistent formatting matters to people.
  • Curly braces form blocks; variables declared in a block exist only inside it.
  • #include <header> makes standard library features available. Include every header you use.
  • Standard library names live in the std namespace; :: reaches into a namespace, as in std::println.
  • Prefer explicit std::, use targeted using std::name; sparingly, and never put using namespace std; in a header.
  • C++ is case-sensitive. When the compiler complains, read the file:line:column and fix the first error first.

Next: Comments, where you'll learn how to leave helpful notes in your code.