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/ # Type Conversions and Casts Based on *C++ Primer, 5th ed.* Section 4.11 (Type Conversions). ## Named Cast Syntax C++ introduces four explicit named casts: ```cpp CASTNAME(EXPRESSION); ``` - **`CASTNAME`:** One of `static_cast`, `const_cast`, `reinterpret_cast`, or `dynamic_cast`. - **Value Category Rule:** If `TYPE` is a reference, the result of the cast is an **lvalue**; otherwise, the result is an **rvalue**. ### The Four Named Casts at a Glance | Cast | Timing | Target / Purpose | Safety Check | | :--- | :--- | :--- | :--- | | **`static_cast`** | Compile-time | Well-defined conversions (arithmetic, `void*` recovery, upcasting) | Validates convertible types at compile time | | **`const_cast`** | Compile-time | Adds or casts away low-level `const` / `volatile` | Compiler ensures types match except for constness | | **`reinterpret_cast`** | Compile-time | Low-level bit pattern reinterpretation | No safety check (platform-dependent, aliasing risks) | | **`dynamic_cast`** | Runtime | Safe Downcasting & Crosscasting in polymorphic hierarchies | Queries RTTI (Run-Time Type Identification) via `vptr` → `vtable` | --- ## 1. `static_cast` Used for any well-defined type conversion that does not involve casting away `const`. ### Common Use Cases 1. **Forcing Floating-Point Division:** ```cpp int i = 2, j = 1; double slope = static_cast(j) / i; // Forces floating-point division ``` 2. **Informing Compiler of Intentional Truncation:** ```cpp double d = 97.6; int n = static_cast(d); // Explicit cast turns off compiler truncation warnings ``` 3. **Retrieving a Pointer from `void*`:** ```cpp double d = 97.6; void *vp = &d; double *dp = static_cast(vp); // Valid: restores original typed pointer // int *ip = static_cast(vp); // Compiles, but Undefined Behavior if dereferenced ``` > When restoring a pointer stored in a `void*` back to its original type via `static_cast`, the pointer value is guaranteed to be preserved. However, the programmer must ensure the target type is the actual type of the object. --- ## 2. `const_cast` The **only** cast that can change low-level `const` or `volatile` qualifiers. ```cpp const char *pc = "hello"; char *p = const_cast(pc); // Casts away const ``` ### Undefined Behavior Warning - **Modifying a const object:** Using `const_cast` to obtain write access and mutate an object originally defined as `const` is **Undefined Behavior (UB)**: ```cpp const int val = 10; int *p = const_cast(&val); *p = 20; // Undefined Behavior: val may reside in read-only memory ``` - **Legal use:** If the underlying object was originally non-`const`, using `const_cast` to regain write access is legal. ### Typical Use Case `const_cast` is most useful in overloaded `const` and non-`const` member functions sharing identical lookup/validation logic, where the **non-`const` version delegates to the `const` member function to avoid code duplication**: ```cpp class Buffer { public: // 1. const member function: implements the core lookup/validation logic once const char& operator[](size_t idx) const { // Bounds checking, logging, and read logic return data_[idx]; } // 2. non-const member function: reuses the const version char& operator[](size_t idx) { // (1) static_cast(*this) (or C++17 std::as_const(*this)) adds const // so overload resolution calls the const operator[] instead of infinite recursion // (2) const_cast(...) strips const from the returned reference // (100% safe because *this in this non-const member function is guaranteed to be non-const!) return const_cast( static_cast(*this)[idx] ); } private: std::string data_; }; ``` > ⚠️ **Warning:** Never do the reverse — having the `const` member function cast away `const` on `this` to call the non-`const` version — as that risks mutating an actually `const` object, causing Undefined Behavior. Always have the **non-`const` overload call the `const` overload**. --- ## 3. `reinterpret_cast` Performs a low-level, machine-dependent reinterpretation of the bit pattern of its operands. ```cpp int n = 42; int *ip = &n; char *pc = reinterpret_cast(ip); // Reinterprets int pointer as char pointer ``` - **Inherent Danger:** Dereferencing the reinterpreted pointer treats the raw bytes of an `int` as characters. `reinterpret_cast` is inherently machine-dependent and circumvents the type system. - **Strict Aliasing:** Accessing an object through a pointer of an incompatible type violates strict aliasing rules, resulting in optimizer-induced Undefined Behavior. --- ## 4. `dynamic_cast` Covered in detail in *C++ Primer* Section 19.2: Run-Time Type Identification (RTTI). Safely converts pointers and references at runtime along a polymorphic class hierarchy — classes with at least one `virtual` function — by inspecting RTTI via `vptr` → `vtable`. For Upcast vs. Downcast, why `virtual` is required, and the full scope of `dynamic_cast` including Crosscast with code examples, see **[OOP: Upcast vs. Downcast]({{< relref "/programming/cpp/primer/oop.md#2-upcast-vs-downcast-and-static-vs-dynamic-type" >}})**. --- ## Old-Style Casts Early C++ supported two old-style cast notations: ```cpp TYPE(EXPRESSION); // Function-style cast notation (TYPE)EXPRESSION; // C-language-style cast notation ``` ### Fallback Order An old-style cast attempts the following named casts in order: 1. `const_cast` 2. `static_cast` 3. `reinterpret_cast` If neither a `const_cast` nor a `static_cast` is legal, the old-style cast **silently falls back to a `reinterpret_cast`**. This makes old-style casts hazardous and difficult to audit. --- ## Core Advice: Avoid Casts > *"Casts interfere with the normal type-checking system. As a result, we strongly recommend that programmers avoid casts."* - *C++ Primer, 5th ed.* - **`reinterpret_cast`:** Always hazardous; avoid whenever possible. - **`const_cast`:** Useful in overloaded functions, but other uses often indicate a design flaw. - **`static_cast` and `dynamic_cast`:** Should be needed infrequently. Re-evaluate design before introducing them. - **Mitigation:** When a cast is unavoidable, limit the scope of the cast value and clearly document all underlying type assumptions.