← Back to Index

C++ Reference

0. Basics

0.1 Hello World

#include <iostream>

int main() {
    // std::cout prints strings to STDOUT
    std::cout << "Hello, World!" << std::endl;
    return 0; // Return 0 to indicate process success
}
TERMINAL OUTPUT
Hello, World!

0.2 Building & Running

C++ is a compiled language. Use g++ or clang++ for compilation.

# Compile source using C++20 standard
g++ -std=c++20 main.cpp -o main

# Execute the compiled binary
./main
TERMINAL OUTPUT
Hello, World!

0.3 Comments

// Single-line comment for brief annotations

/* Multi-line
   comment block for extensive documentation */
TERMINAL OUTPUT
(No output)

0.4 Imports

#include <iostream> // Standard input/output stream
#include <vector>   // Dynamic array container
#include <string>   // String class
#include <map>      // Associative container (dictionary)
TERMINAL OUTPUT
(No output)

0.5 Exit Codes

#include <cstdlib>

int main() {
    // Standard return from main entry point
    // return 1; 
    
    // Immediate process termination with status
    std::exit(1); 
}
TERMINAL OUTPUT
(Process exits with status 1)

0.6 Error Handling

C++ uses exceptions for runtime error management.

#include <iostream>
#include <stdexcept>

int main() {
    try {
        // Explicitly throw a runtime error
        throw std::runtime_error("failed");
    } catch (const std::exception& e) {
        // Catch exception and print its description
        std::cerr << "Error: " << e.what() << std::endl;
    }
    return 0;
}
TERMINAL OUTPUT
Error: failed

1. Environment, Variables & Time

1.1 Variable Declaration

int x = 5;              // Mutable integer
const double PI = 3.14; // Immutable constant
auto name = "C++";      // Automatic type inference (C++11)
TERMINAL OUTPUT
(No output)

1.2 Integer Types & Limits

Size Signed Unsigned
8-bit int8_t uint8_t
32-bit int32_t uint32_t
64-bit int64_t uint64_t

Limits: #include <limits>, std::numeric_limits<int>::max().

1.3 Casting

Prefer static_cast for explicit, safe type conversions.

double d = 3.14;
// Explicitly cast double to int (truncation occurs)
int i = static_cast<int>(d); 
TERMINAL OUTPUT
(No output)

1.4 Environment Variables

#include <cstdlib>

// Retrieve environment variable from system
const char* path = std::getenv("PATH");
TERMINAL OUTPUT
(No output)

1.5 Time Measurement & Formatting

#include <iostream>
#include <chrono>
#include <iomanip>

int main() {
    // High-resolution performance measurement
    auto start = std::chrono::steady_clock::now();
    auto end = std::chrono::steady_clock::now();
    auto elapsed = end - start;

    // Calendar time formatting
    std::time_t t = std::time(nullptr);
    std::cout << std::put_time(std::localtime(&t), "%Y-%m-%d %H:%M:%S") << std::endl;
    return 0;
}
TERMINAL OUTPUT
2024-05-16 12:00:00 (example)

2. Operators & Regex

2.1 Arithmetic & Logic

int a = 10 / 3; // Integer division (3)
double b = 10.0 / 3.0; // Floating point division (3.333)
bool c = true && false; // Logical AND (false)
TERMINAL OUTPUT
(No output)

2.2 Regex & Pattern Matching

Using std::regex (since C++11).

#include <iostream>
#include <regex>
#include <string>

int main() {
    std::string text = "Price: $100";
    std::regex re(R"(\$(\d+))"); // Raw string literal for regex
    std::smatch match;
    // Search for regex pattern in string
    if (std::regex_search(text, match, re)) {
        std::cout << match[1] << std::endl; // Print first capture group
    }
    return 0;
}
TERMINAL OUTPUT
100

3. Argument Parsing

3.1 Argument Parsing

C++ standard library does not provide a built-in CLI flag parser.

#include <string>

int main(int argc, char* argv[]) {
    // Iterate through command line arguments
    for (int i = 1; i < argc; ++i) {
        std::string arg = argv[i];
        if (arg == "-v") { /* Handle verbose flag */ }
        else if (arg == "-o" && i + 1 < argc) {
            std::string out = argv[++i]; // Handle valued flag
        }
    }
    return 0;
}
TERMINAL OUTPUT
(No output)

4. Functions & Memory

4.1 Declaration & Returns

// Basic function with default parameter
int add(int a, int b = 0) { return a + b; }

#include <utility>
// Multi-return via std::pair (structured bindings since C++17)
std::pair<int, bool> getResult() { return {42, true}; }

int main() {
    auto [val, ok] = getResult(); // Unpack pair
    return 0;
}
TERMINAL OUTPUT
(No output)

4.2 References & Pointers

// Pass by reference: modifies the original variable
void increment(int& n) { n++; }

// Pass by pointer: allows null values and explicit dereferencing
void reset(int* n) { if (n) *n = 0; }

#include <iostream>
#include <string>
// Const reference: efficient for large objects, read-only access
void print(const std::string& s) { std::cout << s; }
TERMINAL OUTPUT
(No output)

5. Control Flow

5.1 Conditionals (If/Else)

#include <iostream>

int main() {
    int x = 10;
    // Standard if/else-if/else
    if (x > 10) {
        std::cout << "Greater";
    } else if (x == 10) {
        std::cout << "Equal";
    } else {
        std::cout << "Lesser";
    }

    // Truthiness: 0 is false, non-zero is true
    if (1) { std::cout << " (True)"; }
    
    // If with initializer (C++17)
    if (int y = 5; y > 0) { std::cout << " (Positive)"; }
    
    return 0;
}
TERMINAL OUTPUT
Equal (True) (Positive)

5.2 Switch / Case

#include <iostream>

int main() {
    int val = 2;
    switch (val) {
        case 1: std::cout << "One"; break;
        case 2: std::cout << "Two"; break; // 'break' prevents fallthrough
        default: std::cout << "Other"; break;
    }
    return 0;
}
TERMINAL OUTPUT
Two

5.3 Basic Loops (While/For)

#include <iostream>

int main() {
    // Standard for loop
    for (int i = 0; i < 3; ++i) { std::cout << i; }

    int x = 0;
    // while loop
    while (x < 3) { x++; }

    // do-while loop
    do { x--; } while (x > 0);
    return 0;
}
TERMINAL OUTPUT
012

5.4 Breaking & Continue

#include <iostream>

int main() {
    for (int i = 0; i < 10; ++i) {
        if (i < 2) continue; // Skip to next iteration
        if (i == 5) break;    // Exit loop
        std::cout << i;
    }
    return 0;
}
TERMINAL OUTPUT
234

5.5 Iterating Collections

#include <iostream>
#include <vector>
#include <map>

int main() {
    std::vector<int> myVector = {1, 2};
    // Range-based for loop (since C++11)
    for (const auto& val : myVector) { std::cout << val; }

    std::map<int, int> myMap = {{1, 10}};
    // Structured bindings in range-for (since C++17)
    for (const auto& [key, val] : myMap) {
        std::cout << " " << key << ":" << val;
    }
    return 0;
}
TERMINAL OUTPUT
12 1:10

6. Strings & Files

6.1 String Manipulation

#include <string>

int main() {
    std::string s = " Hello ";
    // Trim starting whitespace using find_first_not_of
    s.erase(0, s.find_first_not_of(' ')); 
    // Substring extraction
    std::string sub = s.substr(0, 2); // Result: "He"
    return 0;
}
TERMINAL OUTPUT
(No output)

6.2 Path Joining

#include <filesystem>
namespace fs = std::filesystem;

int main() {
    // Join path segments using the / operator (C++17)
    fs::path p = fs::path("/") / "usr" / "bin";
    return 0;
}
TERMINAL OUTPUT
(No output)

6.3 Streaming I/O (Chunks)

#include <fstream>

void readChunks() {
    // Open file in binary mode
    std::ifstream f("data.bin", std::ios::binary);
    char buffer[4096]; // 4KB chunk buffer
    while (f.read(buffer, sizeof(buffer))) {
        // gcount() returns the number of bytes read
        std::streamsize n = f.gcount();
    }
}
TERMINAL OUTPUT
(No output)

6.4 Read to Memory

#include <fstream>
#include <sstream>
#include <string>

void readFile() {
    std::ifstream t("file.txt");
    std::stringstream buffer;
    // Read the entire file buffer into the stream
    buffer << t.rdbuf();
    std::string content = buffer.str();
}
TERMINAL OUTPUT
(No output)

7. Binary & Bitwise

7.1 Allocation & Packing

#include <vector>
#include <cstdint>

void packData() {
    std::vector<uint8_t> buf(12);
    uint32_t val = 42;

    // Manual Big-Endian packing using bit shifts
    buf[0] = (val >> 24) & 0xFF;
    buf[1] = (val >> 16) & 0xFF;
    buf[2] = (val >> 8) & 0xFF;
    buf[3] = val & 0xFF;
}
TERMINAL OUTPUT
(No output)

7.2 Bitwise Operations

int res = 0b1010 & 0b1100; // Bitwise AND
res = 0b1010 | 0b1100;      // Bitwise OR
res = 0b1010 ^ 0b1100;      // Bitwise XOR
res = ~0b1010;              // Bitwise NOT (complement)
res = 0b0001 << 2;          // Bitwise Shift Left (0b0100)
TERMINAL OUTPUT
(No output)

7.3 Hex Conversion

#include <sstream>
#include <iomanip>
#include <string>

int main() {
    std::stringstream ss;
    // Convert integer to hex string
    ss << std::hex << 255;
    std::string s = ss.str(); // "ff"

    // Parse hex string to integer
    int val = std::stoi("ff", nullptr, 16); // 255
    return 0;
}
TERMINAL OUTPUT
(No output)

8. Collections & JSON

8.1 Lists, Maps & Sets

#include <vector>
#include <map>
#include <set>

void collections() {
    // Dynamic array
    std::vector<int> v = {1, 2}; v.push_back(3); 
    // Sorted map (balanced BST)
    std::map<std::string, int> m; m["k"] = 1;    
    // Set of unique elements
    std::set<int> s = {1, 1, 2}; // Result: {1, 2}
}
TERMINAL OUTPUT
(No output)

8.2 JSON Parsing

// C++ standard library does not support JSON natively.
// Common third-party libraries: nlohmann/json, RapidJSON.
TERMINAL OUTPUT
(No output)

9. Systems & Networking

9.1 TCP Server & Client

Using POSIX sockets.

#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>

void networking() {
    // Create a TCP stream socket
    int srv = socket(AF_INET, SOCK_STREAM, 0);
    // bind, listen, accept omitted for brevity
    
    int cli = socket(AF_INET, SOCK_STREAM, 0);
    // connect(cli, (struct sockaddr*)&srv_addr, sizeof(srv_addr));
}
TERMINAL OUTPUT
(No output)

9.2 UDP Server & Client

#include <sys/socket.h>
#include <netinet/in.h>

void udp() {
    // Create a UDP datagram socket
    int s = socket(AF_INET, SOCK_DGRAM, 0);
    // sendto(s, "ping", 4, 0, (struct sockaddr*)&target, sizeof(target));
}
TERMINAL OUTPUT
(No output)

9.3 Concurrency

#include <iostream>
#include <thread>

int main() {
    // Spawn a background thread with a lambda function
    std::thread t([]() { 
        std::cout << "Thread running" << std::endl; 
    });
    // Wait for the thread to complete execution
    t.join();
    return 0;
}
TERMINAL OUTPUT
Thread running

9.4 SQLite

#include <cstdlib>

int main() {
    // Execute sqlite3 CLI via system command
    std::system("sqlite3 :memory: \"SELECT 42;\"");
    return 0;
}
TERMINAL OUTPUT
42