C++ Syntax & Structure
In this page:
Semicolons
Every complete statement in C++ must end with a semicolon, which tells the compiler exactly where one instruction stops and the next begins. Forgetting one is one of the most common beginner errors, and it usually causes the compiler to report an error on the following line instead of the one you actually missed.
Example: Semicolons
#include <iostream>
int main() {
int x = 5;
std::cout << x << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Curly Braces
Curly braces { } group multiple statements into a single block, marking where a function body, loop, or if-statement begins and ends. Without braces, some constructs like if only apply to the single statement immediately following them, which is a frequent source of subtle bugs when a second line is added later.
Example: Curly Braces
#include <iostream>
int main() {
if (true) {
std::cout << "Inside the block" << std::endl;
std::cout << "Both lines run" << std::endl;
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Tokens
A token is the smallest meaningful piece the compiler recognizes when it reads your source code — keywords like int, identifiers like variable names, literal values, and operators like + are all tokens. Understanding tokens helps explain compiler error messages, which often point at the specific token where parsing failed.
Example: Tokens
#include <iostream>
int main() {
int total = 5 + 3; // int, total, =, 5, +, 3 are all tokens
std::cout << total << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Case Sensitivity
C++ treats uppercase and lowercase letters as completely different characters, so main and Main are not interchangeable — only lowercase main is recognized as your program's entry point. This same rule means total and Total can coexist as two entirely separate variables, which can cause confusing bugs if used carelessly.
Example: Case Sensitivity
#include <iostream>
int main() {
int total = 1;
int Total = 2; // a completely different variable from 'total'
std::cout << total << " " << Total << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Indentation
Indentation has no effect on how the compiler parses your code — braces alone define the structure — but consistent indentation is what makes nested loops and conditionals readable to a human. Most teams enforce a consistent indentation style precisely because the compiler's leniency here makes it easy for code to become unreadable without one.
Example: Indentation
#include <iostream>
int main() {
for (int i = 0; i < 2; i++) {
if (i == 0) {
std::cout << "Consistent indentation aids readability" << std::endl;
}
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 15 topics to unlock
0/15 topics done
Complete these topics first: