CppC++ Syntax

C++ Syntax

Before diving into variables and control flow, it helps to know the ground rules of how C++ source code is structured — the punctuation and formatting conventions every program follows.

Semicolons terminate statements

Every statement in C++ ends with a semicolon (;). Unlike Python, line breaks don’t matter to the compiler — only the semicolon marks the end of a statement.

CPP
int a = 5;
int b = 10;
int sum = a + b;
The classic missing-semicolon error
Forgetting a semicolon is one of the most common beginner mistakes, and the compiler error it produces often points to the **next** line, not the one actually missing the semicolon — because the compiler doesn’t realize the statement ended until it hits something unexpected. If an error message looks confusing, check the line just above it first.
Curly braces define blocks
Curly braces `{ }` group multiple statements into a single block — used for function bodies, loops, conditionals, and classes. Whitespace and indentation inside braces are purely for human readability; the compiler doesn’t require any particular style.

CPP
if (a > b) {
    std::cout << "a is greater" << std::endl;
} else {
    std::cout << "b is greater or equal" << std::endl;
}
Case sensitivity

C++ is case-sensitive: total, Total, and TOTAL are three different identifiers. Keywords like int, return, and class must always be lowercase.

Whitespace is flexible

Because statements end with semicolons and blocks are delimited by braces, C++ doesn’t care about indentation or line breaks the way Python does. You could write an entire program on one line (please don’t) and it would compile identically to a well-formatted version.

The general structure of a file
  • Includes at the top — pull in standard library or project headers (e.g. #include <iostream>).

  • Declarations — functions, classes, and global constants used by the program.

  • The main function — the program's entry point, required exactly once per executable.

Well-formatted vs poorly-formatted

Both of these compile and run identically — but only one of them is something you’d want to maintain, debug, or hand to a teammate.

Well-formatted

CPP
#include <iostream>

int main() {
    int score = 42;

    if (score > 40) {
        std::cout << "High score!" << std::endl;
    }

    return 0;
}

Technically valid, practically unreadable

CPP
#include <iostream>
int main(){int score=42;if(score>40){std::cout<<"High score!"<<std::endl;}return 0;}

Consistent indentation (usually 2 or 4 spaces per level), spacing around operators, and one statement per line cost nothing at compile time but save enormous amounts of time when reading code later — including your own code, a few months from now.