Cheat Sheet - Linux: /linux/ - CLI: /linux/cli/ - locate vs type vs which vs whereis: /linux/cli/locate-vs-type-vs-which-vs-whereis/ - make: /linux/cli/make/ - awk: /linux/cli/awk/ - find: /linux/cli/find/ - grep: /linux/cli/grep/ - pgrep: /linux/cli/pgrep/ - ps: /linux/cli/ps/ - pstree: /linux/cli/pstree/ - trap: /linux/cli/trap/ - xargs: /linux/cli/xargs/ - Shell: /linux/shell/ - BASH_SOURCE: /linux/shell/bash-source/ - Redirection: /linux/shell/redirection/ - Special Variables: /linux/shell/special-variables/ - Scripting Tips: /linux/shell/script-tips/ - set -o vi: /linux/shell/bash-vi-mode/ - Shell Processing Order: /linux/shell/process-order/ - What are Interactive and Login Shells?: /linux/shell/interactive-login/ - Double Quote Expansion: /linux/shell/shell-expansion/ - System Programming: /linux/system-programming/ - File I/O: /linux/system-programming/file-io/ - Process: /linux/system-programming/process/ - Shared Libraries: /linux/system-programming/shared-libraries/ - Kernel: /linux/kernel/ - Go: /programming/go/ - Concurrency: /programming/go/concurrency/ - CSP (Communicating Sequential Processes) and Channels: /programming/go/concurrency/csp/ - Channel: /programming/go/concurrency/channel/ - Select: /programming/go/concurrency/select/ - sync: /programming/go/concurrency/sync/ - Concurrency Patterns: /programming/go/concurrency/patterns/ - Goroutines and the Go Runtime: /programming/go/concurrency/runtime/ - Standard Library: /programming/go/std/ - os: /programming/go/std/os/ - context: /programming/go/std/context/ - io: /programming/go/std/io/ - json: /programming/go/std/json/ - net/http: /programming/go/std/net-http/ - slog: /programming/go/std/slog/ - testing: /programming/go/std/testing/ - time: /programming/go/std/time/ - Ellipsis (...): /programming/go/ellipsis/ - error: /programming/go/error/ - Function: /programming/go/function/ - Go Tool: /programming/go/tool/ - Interface: /programming/go/interface/ - Map: /programming/go/map/ - Package and Module: /programming/go/package-module/ - Pointer: /programming/go/pointer/ - Slice: /programming/go/slice/ - String: /programming/go/string/ - Switch: /programming/go/switch/ - Comparison: /programming/go/comparison/ - defaultdict: /programming/python/collections/defaultdict/ - heapq: /programming/python/collections/heapq/ - @cache: /programming/python/cache/ - abc: /programming/python/abc/ - bisect: /programming/python/bisect/ - Type Hints: /programming/python/type-hints/ - Passing Mechanism: /programming/python/passing-mechanism/ - uv: /programming/python/uv/ - *args and **kwargs: /programming/python/args-kwargs/ - re: /programming/python/re/ - C: /programming/c/ - Pointers and Arrays: /programming/c/pointer/ - Syntax Basics: /programming/c/syntax-basics/ - static: /programming/c/static/ - Bit Manipulation: /programming/c/bit-manipulation/ - C vs C++: /programming/c/c-vs-cpp/ - stdatomic: /programming/c/stdatomic/ - C++: /programming/cpp/ - RAII (Resource Acquisition Is Initialization): /programming/cpp/raii/ - Copy Elision & Move Semantics: /programming/cpp/copy-elision-and-move-semantics/ - Most Vexing Parse & In-Class Initializer: /programming/cpp/most-vexing-parse/ - C++ Keywords Reference: /programming/cpp/keywords/ - C++ Primer: /programming/cpp/primer/ - Variables and Basic Types: /programming/cpp/primer/variables-and-basic-types/ - Expressions: /programming/cpp/primer/expressions/ - Type Conversions and Casts: /programming/cpp/primer/type-conversions-and-casts/ - Statements: /programming/cpp/primer/statements/ - Functions: /programming/cpp/primer/functions/ - Classes: /programming/cpp/primer/classes/ - The IO Library: /programming/cpp/primer/io-library/ - STL: /programming/cpp/primer/stl/ - Lambda Expressions: /programming/cpp/primer/lambda/ - Smart Pointers: /programming/cpp/primer/smart-pointers/ - Copy Control: /programming/cpp/primer/copy-control/ - Overloaded Operations and Conversions: /programming/cpp/primer/operator-overloading/ - Object-Oriented Programming (OOP): /programming/cpp/primer/oop/ - Templates and Generic Programming: /programming/cpp/primer/templates/ - Namespaces: /programming/cpp/primer/namespaces/ - Pointers to Class Member: /programming/cpp/primer/pointers-to-class-member/ - Advanced: /programming/cpp/advanced/ - Error Handling: /programming/cpp/advanced/error-handling/ - Concurrency & Threading: /programming/cpp/advanced/concurrency/ - Unit Testing: /programming/cpp/advanced/unit-testing/ - Comparison: /programming/comparison/ - Kubernetes: /cloud-devops/kubernetes/ - Fleet: /cloud-devops/kubernetes/gke/fleet/ - Kustomize vs Helm: /cloud-devops/kubernetes/kustomize-vs-helm/ - API Extension: /cloud-devops/kubernetes/api-extension/ - Concept: /cloud-devops/kubernetes/kueue/concept/ - DRA: /cloud-devops/kubernetes/dra/ - Secret Manager: /cloud-devops/terraform/google-secret-manager/ - Knowledge: /network/knowledge/ - PDU: /network/knowledge/osi-model/ - curl: /network/cli/curl/ - Concurrency Concepts: /cs/concurrency-and-parallelism/concepts/ - Concurrency vs Parallelism: /cs/concurrency-and-parallelism/concurrency-vs-parallelism/ - Mutex vs Atomic: /cs/concurrency-and-parallelism/mutex-vs-atomic/ - Regular Expression: /cs/regular-expression/ - Multiplexer vs Dispatcher: /cs/multiplexer-vs-dispatcher/ - Driver and Runtime: /ai-ml/gpu/driver-and-runtime/ - Serving: /ai-ml/serving/ - Dotfiles: /dotfiles/ - Git: /dotfiles/git/ - Cheat Sheet: /dotfiles/git/cheat-sheet/ - revisions: /dotfiles/git/revisions/ - Submodule vs Worktree: /dotfiles/git/submodule-vs-worktree/ - checkout, reset -> switch, restore: /dotfiles/git/checkout-switch-restore-reset/ - rebase: /dotfiles/git/rebase/ - Branching and Merging: /dotfiles/git/branching-merging/ - Vim: /dotfiles/vim/ - Plugin: /dotfiles/vim/plugin/ - auto-pairs: /dotfiles/vim/plugin/auto-pairs/ - vim-commentary: /dotfiles/vim/plugin/vim-commentary/ - vim-easymotion: /dotfiles/vim/plugin/vim-easymotion/ - vim-surround: /dotfiles/vim/plugin/vim-surround/ - Marks: /dotfiles/vim/tips/marks/ - vimrc: /dotfiles/vim/vimrc/ - lf: /dotfiles/lf/ # Statements Key statement syntax and critical caveats based on *C++ Primer, 5th ed.* Chapter 5 (Statements). ## 1. The `if` Statement and Dangling Else In C++, an `else` branch is syntactically paired with the **closest preceding unmatched `if`**. ```cpp if (condition1) if (condition2) DoSomething(); else // Warning: pairs with condition2's if, not condition1! DoAnother(); ``` To eliminate ambiguity and prevent logical bugs, always use explicit curly braces (`{}`) to wrap compound statement blocks. --- ## 2. The `switch` Statement and Bypassing Variable Initialization The curly braces `{ ... }` wrapping the body of a `switch` statement form a single scope. A `case` label is merely a jump target and does not establish a separate nested scope. Consequently, any variable declared after one `case` label remains in scope for all subsequent `case` branches. ### Why Bypassing Initialization is a Compile Error Jumping across a `case` label past a variable definition that has an **explicit initializer (`= val`) or an implicit default constructor** is a **compile-time error**. ```cpp switch (val) { case 1: // string s; // ❌ Compile error: default constructor execution is bypassed // int ix = 42; // ❌ Compile error: explicit initialization (= 42) is bypassed int iy; // ⭕ Valid: primitive variable without initializer can be defined break; case 2: // If execution jumped directly to case 2: iy = 0; // ⭕ Valid: iy is in scope // s.empty(); // If s were allowed, this would access an unconstructed object with corrupt memory break; } ``` - **Primitive Types (`int iy;`):** Without an initializer, this only allocates uninitialized stack storage. The compiler allows it, and `iy` is in scope and accessible in `case 2`. - **Class Objects (`string s;`) and Explicit Initializers (`int ix = 42;`):** Objects require their constructor or initializer code to run. Jumping directly to `case 2` skips this initialization, leaving an unconstructed object in scope. Accessing such an object leads to severe runtime crashes; hence, the compiler prohibits jumping over initializations. > **Solution (Explicit Block Scope):** If a variable must be defined inside a `case`, wrap that `case` in curly braces `{ ... }` to confine the variable's scope. > ```cpp > case 1: { > string s = "hello"; // ⭕ Valid: s is scoped strictly inside this block > break; > } > case 2: > // s is out of scope here > break; > ``` --- ## 3. C++11 Range `for` Statement Used to iterate through all elements of a container or array. ```cpp vector v = {0, 1, 2, 3, 4}; for (auto &r : v) { r *= 2; } ``` ### Compiler Expansion The compiler transforms a range `for` loop into an equivalent iterator-based traditional loop: ```cpp for (auto beg = v.begin(), end = v.end(); beg != end; ++beg) { auto &r = *beg; r *= 2; } ``` ### Important Caveat: Do Not Modify Container Size During Traversal - As shown in the expansion above, **the `end()` iterator is evaluated and cached in `end` once at loop entry**. - Modifying the size of the container (e.g., calling `v.push_back()` or `v.erase()`) inside the loop can invalidate iterators or cause the cached `end` to become out-of-date, leading to undefined behavior. - Therefore, **never add or remove elements from a container inside a range `for` loop.** --- ## 4. `try` Blocks and Exception Handling C++ exception handling consists of `throw`, `try`, and `catch`. ```cpp try { if (val < 0) { throw runtime_error("Negative value not allowed"); } } catch (const runtime_error &err) { cerr << err.what() << '\n'; } catch (...) { // Universal catch-all handler } ``` ### Handler Search and Stack Unwinding 1. When a `throw` executes, execution of the current block immediately halts, and the runtime searches for a matching `catch` handler associated with the current `try` block. 2. If no matching handler is found in the current function, the exception **propagates up to the caller function**. 3. As execution unwinds up the call stack, destructors for all local objects in exited scopes are **automatically invoked** (this process is called **Stack Unwinding**). ### Uncaught Exceptions and Program Abort - If the exception propagates all the way up through `main()` without finding a matching `catch` handler, it becomes an **uncaught exception**. - When an uncaught exception occurs, the C++ runtime calls the standard library function **`std::terminate()`**. - By default, `std::terminate()` invokes **`abort()`**, immediately terminating the program abnormally.