20 topics
/
Quick Reference

C++ Codex

Quick Reference for Professionals

C++17 · Advanced Reference

Program Structure

01
#include <iostream>   // input/output
#include <string>     // strings
#include <vector>     // dynamic arrays

using namespace std;  // opt convenience

int main() {
  // your code here
  cout << "Hello, World!\n";
  return 0;   // 0 = success
}
Tip: Every C++ program needs a main() function — execution starts there.
Deep Dive — ODR · Linkage · C++17

Data Types

02
intWhole numbers · −2B to 2B
long longBig integers · ±9.2×10¹⁸
doubleDecimal numbers (64-bit)
floatDecimal numbers (32-bit)
charSingle character · 'A'
stringText · "hello"
booltrue / false
autoCompiler infers the type
Deep Dive — Integers · Floats · Type Traits

Variables & Constants

03
// Declaration & initialization
int age = 25;
double pi = 3.14159;
string name = "Alice";
bool isReady = true;
auto score = 100;       // type = int

// Constants (cannot be changed)
const int MAX = 100;
constexpr double G = 9.81;
Prefer constexpr over const for compile-time values — it enables use as array sizes, template arguments, and case labels.
Deep Dive — Storage · Init · Scope · constexpr

Input / Output

04
// Output
cout << "Hello";               // print
cout << "Hi" << endl;        // newline
cout << "Hi\n";      // faster newline
cout << "x = " << x << "\n";

// Input
int n;
cin >> n;            // read one value
cin >> a >> b;      // read two values

string line;
getline(cin, line);// read whole line
Deep Dive — Streams · Files · Formatting · sstream

Operators

05
Arithmetic
a + b   a - b   a * b   a / b   a % b
a++   a--   ++a   --a
a += 5   a -= 2   a *= 3   a /= 2
Comparison & Logical
==  !=  <  >  <=  >=    // comparison
&&  ||  !             // AND  OR  NOT
i++ vs ++iPost-increment returns the old value; pre-increment returns the new one.
5 / 2 == 2Integer division truncates. Cast first: (double)5 / 2 → 2.5
&& / ||Short-circuit — right side skipped if result is already known.
precedence* / % bind tighter than + −. Bitwise & | ^ are lower than == !=.
Deep Dive — Precedence · Bitwise · Overloading

If / Else

06
if (x > 0) {
  cout << "positive\n";
} else if (x == 0) {
  cout << "zero\n";
} else {
  cout << "negative\n";
}

// Ternary (shorthand if)
string res = (x > 0) ? "pos" : "neg";
Deep Dive — Init if · constexpr if · optional

Switch Statement

07
switch (day) {
  case 1:
    cout << "Monday";
    break;
  case 2:
    cout << "Tuesday";
    break;
  default:
    cout << "Other";
}
Note: Always use break to prevent fall-through to the next case.
Deep Dive — Fall-Through · Enums · Dispatch

Loops

08
For Loop
for (int i = 0; i < 5; i++) {
  cout << i << " ";   // 0 1 2 3 4
}
While Loop
int i = 0;
while (i < 5) { cout << i++; }
Range-based For (C++11)
vector<int> v = {1, 2, 3};
for (int x : v) { cout << x; }
for (auto x : v) { cout << x; }
Deep Dive — Range-for · Algorithms · Performance

Functions

09
// Declaration (prototype)
int add(int a, int b);

// Definition
int add(int a, int b) {
  return a + b;
}

// Void (no return)
void greet(string name) {
  cout << "Hi " << name << "\n";
}

// Default parameter
void greet(string name = "World") { }

// Call
int result = add(3, 4);   // result = 7
Deep Dive — Passing · Lambdas · RVO · std::function

Arrays

10
Static Array
int arr[5] = {10, 20, 30, 40, 50};
arr[0];             // 10 (index from 0)
arr[2] = 99;        // modify element
2D Array
int grid[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
grid[1][2];          // 6 (row 1, col 2)
Warning: No bounds checking — accessing out-of-range is undefined behavior.
Deep Dive — Decay · std::array · Pointer Arithmetic

Vector (Dynamic Array)

11
#include <vector>

vector<int> v = {1, 2, 3};
v.push_back(4);      // add to end
v.pop_back();        // remove last
v.size();       // number of elements
v.empty();           // is it empty?
v.clear();           // remove all
v[0];                // access element
v.front();  v.back(); // first / last
Deep Dive — Capacity · Iterators · Algorithms · Move

Strings

12
#include <string>

string s = "Hello";
s.length(z);       // 5
s.size();          // same as length()
s[0];              // 'H'
s + " World";      // concatenate
s.substr(1, 3);    // "ell" (pos, len)
s.find("ll");      // index of "ll" → 2
s.replace(0, 1, "J");// "Jello"
stoi("42");        // string → int
to_string(42);     // int → string
Deep Dive — SSO · string_view · Format · Split

Pointers & References

13
Pointers
int x = 10;
int* ptr = &x;   // ptr holds address
*ptr;            // 10 (dereference)
*ptr = 20;       // changes x to 20
References (aliases)
int& ref = x;   // ref IS x (no copy)
ref = 99;        // x is now 99

// Pass by reference (efficient)
void double_it(int& n) { n *= 2; }
Deep Dive — Smart Pointers · Ownership · UB · this

Structs

14
struct Person {
  string name;
  int age;
};

Person p1 = {"Alice", 30};
Person p2;
p2.name = "Bob";
p2.age  = 25;

cout << p1.name;   // Alice
Deep Dive — Layout · Padding · Special Members · POD

Classes (OOP Basics)

15
class Dog {
public:                          // accessible anywhere
  string name;
  int age;

  Dog(string n, int a) : name(n), age(a) {}   // constructor

  void bark() {
    cout << name << " says: Woof!\n";
  }

private:                         // accessible only inside class
  int secret = 42;
};

Dog d("Rex", 3);     // create object
d.bark();            // Rex says: Woof!
cout << d.name;      // Rex
Deep Dive — RAII · Inheritance · Virtual · Access

Useful Algorithms

16
#include <algorithm>

vector<int> v = {3, 1, 4, 1, 5};

sort(v.begin(), v.end());  // ascending
// v = {1,1,3,4,5}

reverse(v.begin(), v.end());

min(3, 7);   max(3, 7);

auto it = find(v.begin(), v.end(), 4);
// it points to 4, or 
// v.end() if not found
Deep Dive — Sorting · Searching · Numeric · Ranges

Math Functions

17
#include <cmath>

sqrt(16.0);    // 4.0
pow(2, 10);    // 1024.0
abs(-5);       // 5
floor(3.9);    // 3.0
ceil(3.1);     // 4.0
round(3.5);    // 4.0
log(2.718);    // ~1.0 (natural log)
log10(100);    // 2.0
Deep Dive — Trig · Random · Limits · C++20 Constants

Common Beginner Mistakes

18
= vs ==Use == to compare. = assigns a value (if (x = 5) is always true!)
Integer division5 / 2 == 2 not 2.5. Cast to double: (double)5 / 2
Array out of boundsAccessing index ≥ size causes undefined behavior — no automatic error.
Missing breakIn switch statements, forgetting break causes fall-through to next case.
Uninitialized varsLocal variables contain garbage — always initialize before use.
endl vs \n\n is faster — endl flushes the buffer every call.
Deep Dive — UB · Memory · Type System · Tools

Compile & Run

19
g++ (most common)
# Compile
g++ main.cpp -o myprogram

# Compile with C++17 + warnings
g++ -std=c++17 -Wall main.cpp -o prog

# Run (Linux/Mac)
./myprogram

# Run (Windows)
myprogram.exe
Deep Dive — Flags · Sanitizers · CMake · Debugging

Dynamic Memory

20
// Allocate on heap
int* p = new int(42);
*p;             // 42
delete p;       // free memory!
p = nullptr;    // good practice

// Array on heap
int* arr = new int[5];
delete[] arr;   // use delete[]
Prefer vector or smart pointers (unique_ptr) over raw new/delete to avoid memory leaks.
Deep Dive — unique_ptr · shared_ptr · weak_ptr · Pools