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.
int a = 5; int b = 10; int sum = a + b;
Curly braces define blocks
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
mainfunction — 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
#include <iostream>
int main() {
int score = 42;
if (score > 40) {
std::cout << "High score!" << std::endl;
}
return 0;
}Technically valid, practically unreadable
#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.