20 topics
/
Quick Reference
CC++++ CCooddeexx
Quick Reference for Professionals
C++17 · Advanced ReferenceProgram 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
Deep Dive — ODR · Linkage · C++17→main() function — execution starts there.Data Types
02| int | Whole numbers · −2B to 2B |
| long long | Big integers · ±9.2×10¹⁸ |
| double | Decimal numbers (64-bit) |
| float | Decimal numbers (32-bit) |
| char | Single character · 'A' |
| string | Text · "hello" |
| bool | true / false |
| auto | Compiler infers the type |
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
Deep Dive — Storage · Init · Scope · constexpr→constexpr over const for compile-time values — it enables use as array sizes, template arguments, and case labels.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 lineDeep Dive — Streams · Files · Formatting · sstream→
Operators
05Arithmetic
Deep Dive — Precedence · Bitwise · Overloading→
a + b a - b a * b a / b a % b a++ a-- ++a --a a += 5 a -= 2 a *= 3 a /= 2Comparison & Logical
== != < > <= >= // comparison && || ! // AND OR NOT
| i++ vs ++i | Post-increment returns the old value; pre-increment returns the new one. |
| 5 / 2 == 2 | Integer 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 == !=. |
If / Else
06if (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
07switch (day) { case 1: cout << "Monday"; break; case 2: cout << "Tuesday"; break; default: cout << "Other"; }
Note: Always use
Deep Dive — Fall-Through · Enums · Dispatch→break to prevent fall-through to the next case.Loops
08For 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 = 7Deep Dive — Passing · Lambdas · RVO · std::function→
Arrays
10Static Array
int arr[5] = {10, 20, 30, 40, 50}; arr[0]; // 10 (index from 0) arr[2] = 99; // modify element2D 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 / lastDeep 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 → stringDeep Dive — SSO · string_view · Format · Split→
Pointers & References
13Pointers
int x = 10; int* ptr = &x; // ptr holds address *ptr; // 10 (dereference) *ptr = 20; // changes x to 20References (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
14struct Person { string name; int age; }; Person p1 = {"Alice", 30}; Person p2; p2.name = "Bob"; p2.age = 25; cout << p1.name; // AliceDeep Dive — Layout · Padding · Special Members · POD→
Classes (OOP Basics)
15class 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; // RexDeep 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 foundDeep 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.0Deep 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 division | 5 / 2 == 2 not 2.5. Cast to double: (double)5 / 2 |
| Array out of bounds | Accessing index ≥ size causes undefined behavior — no automatic error. |
| Missing break | In switch statements, forgetting break causes fall-through to next case. |
| Uninitialized vars | Local variables contain garbage — always initialize before use. |
| endl vs \n | \n is faster — endl flushes the buffer every call. |
Compile & Run
19g++ (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.exeDeep 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
Deep Dive — unique_ptr · shared_ptr · weak_ptr · Pools→vector or smart pointers (unique_ptr) over raw new/delete to avoid memory leaks.