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/ # Functions Based on *C++ Primer, 5th ed.* Chapter 6 (Functions). A function is a block of code with a name. Functions can be overloaded, meaning that the same name may refer to several different functions. ## 1. Object Lifetime and Function Declarations ### Automatic Objects An automatic object is an object that exists only while a block is executing. - **Parameters are automatic objects.** They are created (initialized) when the function is called and destroyed when the block is exited. ### Local `static` Objects Each local `static` object is initialized before the first time execution passes through the object's definition. - **Local `static`s are not destroyed when a function ends; they are destroyed when the program terminates.** ```cpp size_t CountCalls() { static size_t ctr = 0; // Initialized once before execution first passes through return ++ctr; // Persists across calls until the program terminates } int main() { for (size_t i = 0; i != 10; ++i) { cout << CountCalls() << " "; // Prints numbers 1 through 10 } return 0; } ``` ### Header Declarations Functions should be declared in header files and defined in source files. - When validating a function call, the compiler inspects only the declaration in the header file, allowing headers to serve as common interfaces across source files. --- ## 2. Passing Arguments by Reference Passing parameters by reference (`T&` or `const T&`) serves two primary purposes: 1. **When we want to change the value of an argument.** 2. **When copying is expensive or impossible** (e.g., large containers, or non-copyable types like `iostream`). ### Prefer Reference to `const` - **Caveat:** Reference parameters that are not changed inside a function should be references to `const`. - **Use reference to `const` when possible:** - `const T&` can bind to both lvalues and **rvalues**. - Non-const `T&` **cannot bind to rvalues**. - Defining a parameter as plain `T&` when modification is unnecessary prevents callers from passing literals or temporaries, severely restricting the function's usability. > **Modern C++ Exception (Sink Parameters That Must Copy):** When a function or constructor **needs to keep its own copy of the argument anyway**, accept it **by value (`T`)** and `std::move` or `swap` it into place rather than taking `const T&` (when an rvalue argument is passed to the parameter, Copy Elision eliminates the copy completely). See **[Copy Elision & Move Semantics: Two Function Design Rules for Taking Advantage of Copy Elision (RVO)]({{< relref "/programming/cpp/copy-elision-and-move-semantics.md#2-two-function-design-rules-for-taking-advantage-of-copy-elision-rvo" >}})**. --- ## 3. Functions with Varying Parameters C++ provides multiple mechanisms for functions that accept varying numbers of arguments: ### `std::initializer_list` (C++11) Used when all arguments share the same type but their count is variable. - Unlike `vector`, the elements in an `initializer_list` are **always `const` values** (immutable). - It provides `.begin()` and `.end()` member functions, allowing **traversal via range `for` loops**. ```cpp void ErrorMsg(initializer_list il) { for (const auto &elem : il) { // Traversal using .begin() and .end() cout << elem << " "; } cout << endl; } // Pass arguments enclosed in curly braces ErrorMsg({"functionX", "expected", "actual"}); ``` ### Ellipsis Parameter (`...`) Inherited from C for compatibility (e.g., `printf`). - Bypasses compiler type checking, offering no type safety. - Should generally be avoided in C++ except when interfacing with C libraries. --- ## 4. Returning a Pointer to an Array Because we cannot copy an array, a function cannot return an array directly. However, it can return a **pointer or reference to an array**. ### Direct Declaration Syntax Complexity Directly declaring a function that returns a pointer to an array can be intimidating: ```cpp int (*f(int i))[10]; ``` - `f` is a function taking a single `int` parameter and returning a pointer to `int[10]` (`int (*)[10]`). ### Four Ways to Simplify the Declaration #### 1. `typedef` Type Alias Alias either the array type or the pointer-to-array type: ```cpp typedef int arrT[10]; // arrT is an array of ten ints arrT* f1(int i); // returns a pointer to an array of ten ints typedef int (*pointer_to_array)[10]; pointer_to_array f2(int i); ``` #### 2. `using` Alias Declaration (C++11) Equivalent to `typedef` but uses cleaner assignment syntax: ```cpp using arrT = int[10]; arrT* f1(int i); using pointer_to_array = int (*)[10]; pointer_to_array f2(int i); ``` #### 3. Trailing Return Type (C++11) Places the return type after the parameter list using `auto` as the leading placeholder and `-> return_type` after parameters: ```cpp auto f(int i) -> int(*)[10]; // Returns a pointer to an array of ten ints ``` #### 4. Using `decltype` When the target array object already exists and its type is known: ```cpp int odd[] = {1, 3, 5, 7, 9}; int even[] = {0, 2, 4, 6, 8}; // Note: decltype does not decay arrays to pointers; it preserves the array type (int[5]), // so an explicit * is required to return a pointer. decltype(odd) *arrPtr(int i) { return (i % 2) ? &odd : &even; // Returns a pointer to the array } ```