C++ Syntax & Program Structure
C++ programs follow a predictable structure: includes, optional namespace declarations, function definitions, and statements grouped in curly braces. Understanding this shape makes every future program easier to read.
Anatomy of a Program
At the top of a file, #include directives pull in library declarations you plan to use. The using namespace std; line (optional, and often avoided in larger projects) lets you write cout instead of std::cout. The rest of the file is made up of function definitions, with main() as the required starting point.
#include <iostream>
using namespace std;
// A simple function
int square(int n) {
return n * n;
}
int main() {
int result = square(5);
cout << "5 squared is " << result << endl;
return 0;
}
Statements, Blocks, and Comments
A statement is a single instruction, always ending in a semicolon. A block is a group of statements wrapped in curly braces { }, used for function bodies, loops, and conditionals. Comments are ignored by the compiler and exist purely to explain code to humans.
// single line comment/* multi line comment */- Whitespace and indentation are not required by the compiler, but consistent formatting is essential for readability.
Common Mistakes
- Placing
using namespace std;inside header files, which can cause naming conflicts in larger projects. - Mismatched curly braces — always count opens and closes, especially in nested blocks.
- Writing a comment with
//that accidentally spans onto code you meant to keep active. - Case-sensitivity mistakes —
Coutis not the same identifier ascout.
Professional Tip
Most professional C++ codebases avoid a blanket using namespace std; and instead write std::cout explicitly, or import only the specific names they need with using std::cout;. This avoids naming collisions as a project grows.
Your Turn
Write a program with two functions, add and subtract, each taking two integers. In main(), call both and print the results with a properly commented header explaining what the program does.
Mini Quiz
What character must end almost every statement in C++?