Basic Syntax
Every C++ program follows a predictable structure. Understanding why each piece exists — not just what it does — prevents the most common beginner errors and builds a mental model you'll use for the entire course.
Anatomy of a C++ Program
// 1. Preprocessor directive — runs before compilation
#include <iostream>
// 2. Namespace — avoids name collisions
using namespace std;
// 3. Entry point — every C++ program starts here
int main() {
// 4. Statement — must end with semicolon
cout << "Hello, C++!" << endl;
// 5. Return value — 0 = success, non-zero = error
return 0;
}
// Output: Hello, C++!Preprocessor Directives
Lines beginning with # are processed by the preprocessor before the compiler sees your code.
// Include standard library headers
#include <iostream> // Standard I/O (cout, cin)
#include <string> // std::string
#include <vector> // std::vector
#include <cmath> // sin, cos, sqrt, pow
// Include your own headers (use quotes, not angle brackets)
#include "myheader.h"
// Define a constant (no type, no semicolon)
#define PI 3.14159265
// Conditional compilation
#ifdef DEBUG
cout << "Debug mode is ON\n";
#endifNote: Prefer const double PI = 3.14159265; over #define PI — typed constants give you better error messages and respect scoping rules.
The main Function
main is the entry point of every C++ program. The operating system calls it when your program starts.
// Version 1: no command-line arguments
int main() {
return 0;
}
// Version 2: with command-line arguments
int main(int argc, char* argv[]) {
// argc = number of arguments (including program name)
// argv = array of argument strings
for (int i = 0; i < argc; i++) {
cout << "Arg " << i << ": " << argv[i] << "\n";
}
return 0;
}
// ./program hello world
// Output:
// Arg 0: ./program
// Arg 1: hello
// Arg 2: worldThe return value of main becomes the exit code of the process — 0 means success, any other value signals an error.
Namespaces
Namespaces prevent name collisions between different libraries.
#include <iostream>
// Option 1: Always qualify (most explicit, safest in large projects)
std::cout << "Hello\n";
// Option 2: Bring in everything from std (convenient for small programs)
using namespace std;
cout << "Hello\n";
// Option 3: Bring in only specific names (recommended balance)
using std::cout;
using std::endl;
cout << "Hello" << endl;
// Defining your own namespace
namespace myapp {
int version = 1;
void greet() { std::cout << "MyApp v" << version << "\n"; }
}
// Usage
myapp::greet(); // MyApp v1Warning: Avoid using namespace std; in header files — it pollutes the global namespace for every file that includes yours.
Statements and Expressions
Every statement in C++ ends with a semicolon:
int x = 10; // Declaration statement
x = x + 5; // Assignment statement
cout << x << "\n"; // Expression statement
return 0; // Return statement
// Multiple statements on one line (legal but bad style)
int a = 1; int b = 2; int c = a + b;
// A block is a group of statements in curly braces
{
int local = 42; // local only exists inside these braces
cout << local;
}
// cout << local; // ERROR: 'local' not in scope hereComments
// Single-line comment — everything after // is ignored
/*
Multi-line comment
Useful for longer explanations
or temporarily disabling code
*/
/**
* Doxygen-style comment for documentation generation
* @param x The first number
* @param y The second number
* @return Their sum
*/
int add(int x, int y) {
return x + y;
}Basic Output
#include <iostream>
using namespace std;
int main() {
// cout = character output stream
cout << "Hello"; // Print without newline
cout << " World\n"; // \n = newline character
cout << "Line 2" << endl; // endl = newline + flush buffer
// Printing multiple values with << (chaining)
int age = 25;
double pi = 3.14159;
cout << "Age: " << age << ", Pi: " << pi << "\n";
// Escape sequences
cout << "Tab:\tEnd\n";
cout << "Quote: \"Hello\"\n";
cout << "Backslash: \\\n";
return 0;
}
// Output:
// Hello World
// Line 2
// Age: 25, Pi: 3.14159
// Tab: End
// Quote: "Hello"
// Backslash: \C++ Tokens
The compiler breaks your code into tokens — the smallest meaningful units:
| Token type | Examples |
|---|---|
| Keywords | int, if, for, class, return, void |
| Identifiers | main, myVariable, MyClass |
| Literals | 42, 3.14, 'A', "Hello" |
| Operators | +, -, *, /, =, ==, << |
| Punctuation | {, }, (, ), ;, , |
Identifier rules:
- Must start with a letter or underscore
- Can contain letters, digits, and underscores
- Case-sensitive (
myVar≠myvar) - Cannot be a C++ keyword
Common Mistakes in Syntax
// Missing semicolon
int x = 10 // ERROR: expected ';' before '}'
// Wrong bracket type
cout << "Hello"; // Correct: angle brackets for std lib
#include "iostream" // Wrong: should use <iostream>
// Assignment vs equality
if (x = 5) { } // WARNING: this assigns 5 to x, always true
if (x == 5) { } // Correct: tests if x equals 5
// Case sensitivity
Int x = 10; // ERROR: 'Int' is not a type; 'int' is
COUT << "hi"; // ERROR: should be 'cout'Practical Example: A Structured Program
#include <iostream>
#include <string>
// Global constant (available throughout the file)
const std::string APP_NAME = "C++ Demo";
const int VERSION = 1;
// Forward declaration — tells the compiler the function exists
void printBanner();
int main() {
printBanner();
// Local variables
std::string userName;
int userAge;
// Prompt user
std::cout << "Enter your name: ";
std::cin >> userName;
std::cout << "Enter your age: ";
std::cin >> userAge;
// Output with expression
std::cout << "Hello, " << userName << "!\n";
std::cout << "In 10 years you will be " << (userAge + 10) << "\n";
return 0;
}
// Function definition (below main — allowed because of forward declaration)
void printBanner() {
std::cout << "======================\n";
std::cout << " " << APP_NAME << " v" << VERSION << "\n";
std::cout << "======================\n";
}
// Output:
// ======================
// C++ Demo v1
// ======================
// Enter your name: Alice
// Enter your age: 30
// Hello, Alice!
// In 10 years you will be 40Summary
- Every C++ program has exactly one
main()function — execution starts there #includelines are processed by the preprocessor before compilation- Namespaces prevent name collisions; avoid
using namespace std;in headers - Every statement ends with a semicolon — missing one is among the most common errors
cout <<outputs to the screen;"\n"orendlmoves to a new line- C++ is case-sensitive —
Int,INT, andintare completely different - Use
//for single-line comments and/* */for multi-line comments
Next, we'll learn about variables and data types — how to store and work with different kinds of data in C++.