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/ # Variables and Basic Types Based on *C++ Primer, 5th ed.* Chapter 2 (Variables and Basic Types). ## Type Definition The type of an object defines the **data** that an object might contain and what **operations** that object can perform. Among the operations that many types support is the ability to **convert** objects of the given type to other, related types. ## String Literal The type of a string literal is `const char *`. See [String Literal Typing]({{< relref "/programming/c/c-vs-cpp.md#string-literal-typing" >}}). --- ## Initialization vs. Assignment It is tempting to think of initialization as a form of assignment, but initialization and assignment are different operations in C++. - **Initialization is not assignment** - **Initialization** happens when a variable is given a value when it is created. (Invokes a constructor) - **Assignment** obliterates an object's current value and replaces that value with a new one. (Invokes `operator=`) ### Syntax Support | Syntax Form | Initialization (Creation) | Assignment (Existing Variable) | In-Class Initializer | Notes | | :--- | :---: | :---: | :---: | :--- | | `=` | ✅ Valid | ✅ Valid | ✅ Valid | Copy initialization / assignment | | `()` | ✅ Valid | ❌ Compile Error | ❌ Compile Error | Direct initialization; rejected in-class to avoid ambiguity | | `{}` | ✅ Valid | ❌ Compile Error | ✅ Valid | List initialization (C++11); resolves Most Vexing Parse | | `= {}` | ✅ Valid | ✅ Valid | ✅ Valid | List assignment / In-class initialization (C++11) | ```cpp // Initialization forms int a = 10; // Copy initialization int b(10); // Direct initialization int c{10}; // List initialization (C++11) // Assignment forms a = 20; // Valid: assignment operator // a(20); // Compile error: expression cannot be used as a function // a{20}; // Compile error: syntax error a = {20}; // Valid: list assignment ``` ### Most Vexing Parse and In-Class Initializers For a detailed breakdown of patterns and scope differences, see [Most Vexing Parse & In-Class Initializer]({{< relref "/programming/cpp/most-vexing-parse.md" >}}). - **Most Vexing Parse (Function Declaration Ambiguity in Local Scope):** Inside a function body, direct initialization with `()` is allowed (`int b(10);`), but **any construct that can be parsed as a function declaration (`Widget w();`, `Bar b(Foo());`) is silently parsed as a function declaration** rather than an object instantiation. ```cpp Widget w(); // ⚠️ Parsed as a function declaration returning Widget, not an object creation Bar b(Foo()); // ⚠️ Parsed as a function declaration taking Foo (*)() and returning Bar Widget w{}; // ✅ Object creation guaranteed (C++11 list initialization) ``` - **In-Class Initializers (`()` Prohibited Outright):** Inside a class definition (`struct`/`class`), to prevent parser ambiguity with member function declarations at the grammar level, C++ **prohibits `()` for in-class member initializers altogether as a compile error** even with literal arguments (only `{}` or `=` are allowed). ```cpp struct Data { int a = 0; // ✅ Valid int b{0}; // ✅ Valid // int c(0); // ❌ Compile error: parentheses () are banned outright for in-class initializers }; ``` ### Direct vs. Copy Initialization - **Copy Initialization (`=`):** Conceptually creates a temporary object from the right-hand side and copies/moves it into the target object. - **Direct Initialization (`()`, `{}`):** Directly invokes the matching constructor on the object's storage. ```cpp string s1 = "hiya"; // Copy initialization string s2("hiya"); // Direct initialization string s3{"hiya"}; // List initialization (direct) ``` - **Performance (Copy Elision):** There is **zero performance difference**. Compilers perform copy elision to construct the object directly in place without creating temporaries (standardized as Guaranteed Copy Elision in C++17). - **Safety Difference (`explicit` Constructors):** - Direct initialization can invoke `explicit` constructors. - Copy initialization cannot invoke `explicit` constructors, preventing unintended implicit conversions. ```cpp vector v1(10); // Valid: direct initialization invokes explicit constructor (size 10) // vector v2 = 10; // Compile error: copy initialization rejects explicit constructors ``` --- ## Reference vs. Pointer A reference is not an object, which means a reference does not have an address. Instead, a reference is just another name for an already existing **object**. - There is no way to rebind a reference to refer to a different object. - Because there is no way to rebind a reference, references must be initialized. - Because references are not objects, we may not define a reference to a reference. Unlike a reference, a pointer is an **object** in its own right. Hence: - Pointers have an address and can be reassigned. - We may not define a pointer to a reference. `nullptr` is a literal that has a special type that can be converted to any other pointer type. --- ## const Qualifier Because we cannot change the value of a `const` object after we create it, it must be initialized. ### const Reference A "const reference" is formally a **reference to const**. - Because a reference cannot be rebound to another object, a reference itself is implicitly immutable (acting like a top-level `const`). - Therefore, the term "const reference" inherently implies a **low-level `const`** (meaning the referenced object is `const`, not the reference itself). #### Initialization Exceptions (Binding to Temporaries and Rvalues) While an ordinary reference (`T&`) must bind to an lvalue of the exact same type, a **reference to const** (`const T&`) has an exception: it can be initialized from any expression that can be converted to the reference's type (for the evolution and binding rules across `T&` -> `const T&` -> `T&&`, see [Copy Elision & Move Semantics: Evolution of Reference Types & Binding Rules]({{< relref "/programming/cpp/copy-elision-and-move-semantics.md#3-evolution-of-reference-types--binding-rules-t---const-t---t" >}})). - Can bind to non-const lvalues, literals, rvalues, or expressions of a different convertible type. - **Temporary Object Creation:** The compiler creates an unnamed **temporary object** to hold the converted value and binds the reference to that temporary. - **Lifetime Extension:** The lifetime of the temporary object is automatically extended to match the lifetime of the `const T&` bound to it. ```cpp double dval = 3.14; const int &ri = dval; // Valid: compiler creates 'const int temp = dval;' and binds ri to temp const int &r2 = 42; // Valid: binds to temporary holding 42 (rvalue/literal) const int &r3 = r2 * 2; // Valid: binds to temporary holding expression result // int &r4 = dval; // Compile error: ordinary reference cannot bind to temporary // int &r5 = 42; // Compile error: cannot bind non-const lvalue reference to rvalue ``` > **Why non-const references reject temporaries:** If `int &r4 = dval;` were allowed, assigning `r4 = 10;` would modify the hidden temporary object, leaving `dval` untouched. Because this almost certainly contradicts programmer intent, C++ forbids binding non-const references to temporaries. ### Top-Level vs. Low-Level const - **Top-level const:** Indicates that the object (or pointer) itself is a `const`. - `T *const ptr`: Pointer itself is const. - `const int ci = 42`: Variable itself is const. - **Low-level const:** Indicates that the compound type refers/points to a `const` object. - `const T* ptr` or `T const* ptr`: Object pointed to is const. - `const T& ref`: Referenced object is const. (References to const are always low-level const). ```cpp int i = 0; int *const p1 = &i; // Top-level const: p1 cannot be changed const int ci = 42; // Top-level const: ci cannot be changed const int *p2 = &ci; // Low-level const: *p2 cannot be changed const int *const p3 = p2; // Right const is top-level; left const is low-level const int &r = ci; // Low-level const: references to const are always low-level ``` ### Copying Objects When we copy an object, **top-level `const`s are ignored**. On the other hand, **low-level `const` is never ignored**. ```cpp i = ci; // Valid: ci has top-level const; value is copied into i p2 = p1; // Valid: p1 has top-level const; converting int* to const int* is allowed // int *p = p2; // Error: p2 has low-level const; cannot discard const qualifier ```