C++ Basic Syntax Cheatsheet

12 min read

This fundamental C++ syntax and concepts. For more advanced topics, consider studying templates, inheritance, polymorphism, lambda expressions, and modern C++ features (C++11/14/17/20).
Table of Contents
- Basic Program Structure
- Data Types
- Variables & Constants
- Operators
- Control Structures
- Functions
- Arrays
- Pointers & References
- Classes & Objects
- Input/Output
- Memory Management
- STL Basics
Basic Program Structure
#include <iostream> // Include header files
#include <vector>
#include <string>
using namespace std; // Optional: use standard namespace
int main() { // Main function - program entry point
cout << "Hello, World!" << endl;
return 0; // Return 0 for successful execution
}
Comments
// Single line comment
/*
Multi-line comment
Can span multiple lines
*/
Data Types
Fundamental Types
// Integer types
int num = 42; // 32-bit integer
short s = 10; // 16-bit integer
long l = 100000L; // 32/64-bit integer
long long ll = 123456789LL; // 64-bit integer
// Unsigned versions
unsigned int unum = 42U;
unsigned short us = 10U;
unsigned long ul = 100000UL;
// Floating point
float f = 3.14f; // 32-bit float
double d = 3.14159; // 64-bit double
long double ld = 3.14159L; // Extended precision
// Character types
char c = 'A'; // Single character
char str[] = "Hello"; // C-style string
string s = "Hello"; // C++ string (needs #include <string>)
// Boolean
bool flag = true; // true or false
bool flag2 = false;
Type Modifiers
signed int si = -42; // Can be negative (default)
unsigned int ui = 42; // Only positive values
const int CI = 100; // Cannot be modified
static int counter = 0; // Retains value between function calls
Variables & Constants
Variable Declaration
int x; // Declaration
int y = 10; // Declaration with initialization
int a = 5, b = 10, c; // Multiple variables
// Auto keyword (C++11)
auto num = 42; // Compiler deduces type (int)
auto pi = 3.14; // Compiler deduces type (double)
Constants
const int MAX_SIZE = 100; // Compile-time constant
const double PI = 3.14159;
// C++11 constexpr
constexpr int BUFFER_SIZE = 1024;
// #define preprocessor (avoid in modern C++)
#define MAX_VALUE 255
Scope
int global_var = 10; // Global scope
int main() {
int local_var = 20; // Local scope
{
int block_var = 30; // Block scope
}
// block_var not accessible here
return 0;
}
Operators
Arithmetic Operators
int a = 10, b = 3;
int sum = a + b; // Addition: 13
int diff = a - b; // Subtraction: 7
int product = a * b; // Multiplication: 30
int quotient = a / b; // Division: 3 (integer division)
int remainder = a % b; // Modulus: 1
// Compound assignment
a += 5; // a = a + 5
a -= 3; // a = a - 3
a *= 2; // a = a * 2
a /= 4; // a = a / 4
a %= 3; // a = a % 3
Increment/Decrement
int x = 5;
++x; // Pre-increment: x becomes 6, returns 6
x++; // Post-increment: returns 6, then x becomes 7
--x; // Pre-decrement: x becomes 6, returns 6
x--; // Post-decrement: returns 6, then x becomes 5
Comparison Operators
int a = 5, b = 10;
bool equal = (a == b); // Equal to: false
bool not_equal = (a != b); // Not equal to: true
bool less = (a < b); // Less than: true
bool less_eq = (a <= b); // Less than or equal: true
bool greater = (a > b); // Greater than: false
bool greater_eq = (a >= b); // Greater than or equal: false
Logical Operators
bool p = true, q = false;
bool and_result = p && q; // Logical AND: false
bool or_result = p || q; // Logical OR: true
bool not_result = !p; // Logical NOT: false
Bitwise Operators
int a = 5; // Binary: 101
int b = 3; // Binary: 011
int and_op = a & b; // Bitwise AND: 1 (001)
int or_op = a | b; // Bitwise OR: 7 (111)
int xor_op = a ^ b; // Bitwise XOR: 6 (110)
int not_op = ~a; // Bitwise NOT: -6
int left_shift = a << 1; // Left shift: 10 (1010)
int right_shift = a >> 1; // Right shift: 2 (10)
Control Structures
If-Else Statements
int score = 85;
if (score >= 90) {
cout << "Grade A" << endl;
} else if (score >= 80) {
cout << "Grade B" << endl;
} else if (score >= 70) {
cout << "Grade C" << endl;
} else {
cout << "Grade F" << endl;
}
// Ternary operator
string result = (score >= 60) ? "Pass" : "Fail";
Switch Statement
int choice = 2;
switch (choice) {
case 1:
cout << "Option 1 selected" << endl;
break;
case 2:
cout << "Option 2 selected" << endl;
break;
case 3:
cout << "Option 3 selected" << endl;
break;
default:
cout << "Invalid choice" << endl;
break;
}
Loops
For Loop
// Traditional for loop
for (int i = 0; i < 10; i++) {
cout << i << " ";
}
// Range-based for loop (C++11)
vector<int> numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
cout << num << " ";
}
// Auto with range-based for
for (auto& num : numbers) {
num *= 2; // Modify original values
}
While Loop
int count = 0;
while (count < 5) {
cout << count << " ";
count++;
}
Do-While Loop
int num;
do {
cout << "Enter a positive number: ";
cin >> num;
} while (num <= 0);
Loop Control
for (int i = 0; i < 10; i++) {
if (i == 3) {
continue; // Skip rest of this iteration
}
if (i == 7) {
break; // Exit the loop
}
cout << i << " ";
}
Functions
Function Declaration and Definition
// Function declaration (prototype)
int add(int a, int b);
void printMessage();
double calculateArea(double radius);
// Function definition
int add(int a, int b) {
return a + b;
}
void printMessage() {
cout << "Hello from function!" << endl;
}
double calculateArea(double radius) {
return 3.14159 * radius * radius;
}
Function Parameters
// Pass by value
void func1(int x) {
x = 10; // Only local copy is modified
}
// Pass by reference
void func2(int& x) {
x = 10; // Original variable is modified
}
// Pass by pointer
void func3(int* x) {
*x = 10; // Original variable is modified
}
// Const parameters
void func4(const int& x) {
// x cannot be modified
}
Default Parameters
void greet(string name = "World", int times = 1) {
for (int i = 0; i < times; i++) {
cout << "Hello, " << name << "!" << endl;
}
}
// Usage
greet(); // Uses defaults: "World", 1
greet("Alice"); // Uses default times: 1
greet("Bob", 3); // No defaults used
Function Overloading
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
Arrays
Static Arrays
// Declaration and initialization
int arr1[5]; // Uninitialized array
int arr2[5] = {1, 2, 3, 4, 5}; // Initialized array
int arr3[] = {1, 2, 3}; // Size inferred from initializer
int arr4[5] = {1, 2}; // Partially initialized (rest are 0)
// Accessing elements
arr1[0] = 10; // Set first element
int first = arr2[0]; // Get first element
// Array size
int size = sizeof(arr2) / sizeof(arr2[0]);
Multidimensional Arrays
// 2D array
int matrix[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
// Accessing 2D array elements
matrix[1][2] = 100; // Set element at row 1, column 2
int value = matrix[0][3]; // Get element at row 0, column 3
Dynamic Arrays (Vectors)
#include <vector>
vector<int> vec1; // Empty vector
vector<int> vec2(5); // Vector with 5 elements (default initialized)
vector<int> vec3(5, 10); // Vector with 5 elements, all set to 10
vector<int> vec4 = {1, 2, 3, 4, 5}; // Initialized with values
// Vector operations
vec1.push_back(42); // Add element to end
vec1.pop_back(); // Remove last element
int size = vec1.size(); // Get size
bool empty = vec1.empty(); // Check if empty
vec1.clear(); // Remove all elements
Pointers & References
Pointers
int x = 42;
int* ptr = &x; // Pointer to x
int** pptr = &ptr; // Pointer to pointer
// Dereferencing
int value = *ptr; // Get value pointed to
*ptr = 100; // Change value through pointer
// Pointer arithmetic
int arr[] = {1, 2, 3, 4, 5};
int* p = arr; // Points to first element
p++; // Points to second element
p += 2; // Points to fourth element
// Null pointer
int* nullPtr = nullptr; // C++11 way
int* nullPtr2 = NULL; // C way (avoid in modern C++)
References
int x = 42;
int& ref = x; // Reference to x (must be initialized)
// Using reference
ref = 100; // Changes x to 100
int y = ref; // y gets value of x
// References in functions
void swap(int& a, int& b) {
int temp = a;
a = b;
b = temp;
}
Classes & Objects
Basic Class Definition
class Rectangle {
private:
double width;
double height;
public:
// Constructor
Rectangle(double w, double h) : width(w), height(h) {}
// Default constructor
Rectangle() : width(0), height(0) {}
// Destructor
~Rectangle() {
// Cleanup code here
}
// Member functions
double getArea() const {
return width * height;
}
void setWidth(double w) {
width = w;
}
double getWidth() const {
return width;
}
};
// Using the class
Rectangle rect1(5.0, 3.0);
Rectangle rect2;
rect2.setWidth(4.0);
double area = rect1.getArea();
Access Specifiers
class Example {
public:
int publicVar; // Accessible from anywhere
private:
int privateVar; // Only accessible within class
protected:
int protectedVar; // Accessible in class and derived classes
};
Constructors and Destructors
class MyClass {
private:
int* data;
int size;
public:
// Default constructor
MyClass() : data(nullptr), size(0) {}
// Parameterized constructor
MyClass(int s) : size(s) {
data = new int[size];
}
// Copy constructor
MyClass(const MyClass& other) : size(other.size) {
data = new int[size];
for (int i = 0; i < size; i++) {
data[i] = other.data[i];
}
}
// Destructor
~MyClass() {
delete[] data;
}
// Assignment operator
MyClass& operator=(const MyClass& other) {
if (this != &other) {
delete[] data;
size = other.size;
data = new int[size];
for (int i = 0; i < size; i++) {
data[i] = other.data[i];
}
}
return *this;
}
};
Input/Output
Console I/O
#include <iostream>
using namespace std;
int main() {
// Output
cout << "Hello, World!" << endl;
cout << "Number: " << 42 << endl;
// Input
int age;
string name;
cout << "Enter your name: ";
cin >> name; // Reads until whitespace
cout << "Enter your age: ";
cin >> age;
// Read entire line
cin.ignore(); // Clear the input buffer
cout << "Enter a sentence: ";
getline(cin, name); // Reads entire line including spaces
return 0;
}
File I/O
#include <fstream>
#include <iostream>
#include <string>
// Writing to file
void writeToFile() {
ofstream outFile("example.txt");
if (outFile.is_open()) {
outFile << "Hello, File!" << endl;
outFile << "Line 2" << endl;
outFile.close();
}
}
// Reading from file
void readFromFile() {
ifstream inFile("example.txt");
string line;
if (inFile.is_open()) {
while (getline(inFile, line)) {
cout << line << endl;
}
inFile.close();
}
}
Memory Management
Dynamic Memory Allocation
// C-style (avoid in modern C++)
int* ptr = (int*)malloc(sizeof(int) * 10);
free(ptr);
// C++ style
int* ptr2 = new int; // Allocate single int
int* arr = new int[10]; // Allocate array of 10 ints
delete ptr2; // Deallocate single object
delete[] arr; // Deallocate array
// Initialize during allocation
int* ptr3 = new int(42); // Allocate and initialize to 42
int* arr2 = new int[5]{1, 2, 3, 4, 5}; // Allocate and initialize array
Smart Pointers (C++11)
#include <memory>
// unique_ptr - exclusive ownership
unique_ptr<int> ptr1 = make_unique<int>(42);
unique_ptr<int[]> arr1 = make_unique<int[]>(10);
// shared_ptr - shared ownership
shared_ptr<int> ptr2 = make_shared<int>(42);
shared_ptr<int> ptr3 = ptr2; // Both point to same object
// weak_ptr - non-owning observer
weak_ptr<int> weakPtr = ptr2;
STL Basics
Common Containers
#include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <stack>
// Vector - dynamic array
vector<int> vec = {1, 2, 3, 4, 5};
vec.push_back(6);
vec.pop_back();
// List - doubly linked list
list<int> lst = {1, 2, 3};
lst.push_front(0);
lst.push_back(4);
// Map - key-value pairs
map<string, int> ages;
ages["Alice"] = 25;
ages["Bob"] = 30;
ages.insert({"Charlie", 35});
// Set - unique elements
set<int> numbers = {3, 1, 4, 1, 5}; // Only {1, 3, 4, 5} stored
numbers.insert(2);
// Stack - LIFO
stack<int> stk;
stk.push(10);
stk.push(20);
int top = stk.top(); // 20
stk.pop();
// Queue - FIFO
queue<int> q;
q.push(10);
q.push(20);
int front = q.front(); // 10
q.pop();
Iterators
vector<int> vec = {1, 2, 3, 4, 5};
// Iterator-based loop
for (vector<int>::iterator it = vec.begin(); it != vec.end(); ++it) {
cout << *it << " ";
}
// Auto with iterators (C++11)
for (auto it = vec.begin(); it != vec.end(); ++it) {
cout << *it << " ";
}
// Range-based for loop (C++11)
for (auto& element : vec) {
cout << element << " ";
}
Common Algorithms
#include <algorithm>
vector<int> vec = {3, 1, 4, 1, 5, 9, 2, 6};
// Sorting
sort(vec.begin(), vec.end()); // Ascending
sort(vec.begin(), vec.end(), greater<int>()); // Descending
// Searching
auto it = find(vec.begin(), vec.end(), 4);
if (it != vec.end()) {
cout << "Found 4 at position " << (it - vec.begin()) << endl;
}
// Counting
int count = count(vec.begin(), vec.end(), 1); // Count occurrences of 1
// Min/Max
auto minIt = min_element(vec.begin(), vec.end());
auto maxIt = max_element(vec.begin(), vec.end());
Common Patterns & Best Practices
RAII (Resource Acquisition Is Initialization)
class FileHandler {
private:
ifstream file;
public:
FileHandler(const string& filename) : file(filename) {
if (!file.is_open()) {
throw runtime_error("Cannot open file");
}
}
~FileHandler() {
if (file.is_open()) {
file.close();
}
}
// Disable copy to prevent issues
FileHandler(const FileHandler&) = delete;
FileHandler& operator=(const FileHandler&) = delete;
};
Error Handling
#include <stdexcept>
try {
int result = divide(10, 0);
} catch (const exception& e) {
cout << "Error: " << e.what() << endl;
} catch (...) {
cout << "Unknown error occurred" << endl;
}
// Custom exception
class DivideByZeroException : public exception {
public:
const char* what() const noexcept override {
return "Division by zero error";
}
};
0
Subscribe to my newsletter
Read articles from Anni Huang directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Anni Huang
Anni Huang
I am Anni HUANG, a software engineer with 3 years of experience in IDE development and Chatbot.