YouTip LogoYouTip

Cpp Functions

# C++ Functions: A Comprehensive Guide In C++, a **function** is a grouped block of statements that together perform a specific task. Every executable C++ program has at least one functionβ€”the `main()` function. Well-structured programs break down complex logic into smaller, reusable, and modular functions. Functions are also referred to as methods (especially in Object-Oriented Programming), subroutines, or procedures. --- ## 1. Defining a Function A C++ function definition consists of a **header** and a **body**. The general syntax is as follows: ```cpp return_type function_name( parameter_list ) { // Body of the function } ``` ### Components of a Function Definition: * **Return Type (`return_type`):** Specifies the data type of the value the function returns. If a function performs operations but does not return a value, its return type is `void`. * **Function Name (`function_name`):** The actual name of the function. Together, the function name and its parameter list constitute the **function signature**. * **Parameter List (`parameter_list`):** Placeholders for values passed to the function when it is called. The parameter list specifies the types, order, and number of parameters. Parameters are optional; a function may contain no parameters. * **Function Body:** A block of statements enclosed in curly braces `{}` that defines what the function does. ### Example Definition Below is the source code for a function named `max()`. This function takes two integer parameters, `num1` and `num2`, and returns the larger of the two: ```cpp // Function returning the max between two numbers int max(int num1, int num2) { // Local variable declaration int result; if (num1 > num2) result = num1; else result = num2; return result; } ``` --- ## 2. Function Declarations A **function declaration** (or prototype) tells the compiler about a function's name, return type, and parameters. This allows the compiler to verify calls to the function before its actual body is defined. The syntax for a function declaration is: ```cpp return_type function_name( parameter_list ); ``` For the `max()` function defined above, the declaration is: ```cpp int max(int num1, int num2); ``` In declarations, parameter names are optional; only their types are required. Therefore, the following is also a valid declaration: ```cpp int max(int, int); ``` > **Note:** A function declaration is required when you define a function in one source file and call it in another, or when you call a function before its definition appears in the same file. --- ## 3. Calling a Function When a program calls a function, program control is transferred to the called function. The function executes its defined task, and when its `return` statement is executed or its closing brace is reached, it returns control back to the main program. To call a function, you pass the required arguments along with the function name. If the function returns a value, you can store it in a variable. ### Complete Code Example ```cpp #include using namespace std; // Function declaration (prototype) int max(int num1, int num2); int main () { // Local variable declarations int a = 100; int b = 200; int ret; // Calling the function to get the max value ret = max(a, b); cout << "Max value is : " << ret << endl; return 0; } // Function definition int max(int num1, int num2) { int result; if (num1 > num2) result = num1; else result = num2; return result; } ``` ### Output ```text Max value is : 200 ``` --- ## 4. Function Arguments & Passing Methods If a function is to use arguments, it must declare variables that accept the values of these arguments. These are called the **formal parameters** of the function. Formal parameters behave like local variables inside the function; they are created upon entering the function and destroyed upon exiting. There are three primary ways to pass arguments into a function in C++: | Passing Method | Description | | :--- | :--- | | **Call by Value** | Copies the actual value of an argument into the formal parameter of the function. Changes made to the parameter inside the function have **no effect** on the original argument. (This is the default method in C++). | | **Call by Pointer** | Copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument. Changes made to the parameter **will affect** the original argument. | | **Call by Reference** | Copies the reference of an argument into the formal parameter. Inside the function, the reference is used to access the actual argument directly. Changes made to the parameter **will affect** the original argument. | --- ## 5. Default Parameter Values C++ allows you to specify default values for parameters in the function declaration or definition. If a parameter is omitted during a function call, the compiler automatically applies the default value. Default values are assigned using the assignment operator (`=`) in the parameter list. ### Example: Default Parameters ```cpp #include using namespace std; // Function declaration with a default parameter int sum(int a, int b = 20) { int result; result = a + b; return (result); } int main () { int a = 100; int b = 200; int result; // Calling the function with both arguments result = sum(a, b); cout << "Total value is: " << result << endl; // Calling the function with only one argument (b defaults to 20) result = sum(a); cout << "Total value is: " << result << endl; return 0; } ``` ### Output ```text Total value is: 300 Total value is: 120 ``` --- ## 6. Lambda Functions and Expressions (C++11) Introduced in C++11, **Lambda expressions** (often called lambdas) allow you to define anonymous, inline functions. Lambdas can be treated as objects, meaning they can be assigned to variables, passed as arguments, and evaluated on the fly. ### Syntax The basic syntax of a Lambda expression is: ```cpp (parameters) -> return-type { body } ``` * **``**: The capture clause, which defines how variables from the surrounding scope are accessed inside the lambda. * **`(parameters)`**: The parameter list (optional if no parameters are needed). * **`-> return-type`**: The trailing return type (optional; the compiler can often deduce this automatically). * **`{ body }`**: The body of the lambda function. ### Basic Examples **A simple lambda returning a boolean:** ```cpp [](int x, int y) { return x < y; } ``` **A lambda with no return value (returns `void`):** ```cpp [](int x) { cout << "Value: " << x; } ``` **Explicitly declaring a return type:** ```cpp [](int x, int y) -> int { int z = x + y; return z + x; } ``` ### Variable Captures (Closures) Unlike standard functions, lambdas can capture variables from their enclosing scope. You can specify how variables are captured using the capture bracket `[]`: | Capture Syntax | Description | | :--- | :--- | | `[]` | No external variables are captured. Using external variables inside the body will cause a compilation error. | | `[x, &y]` | `x` is captured by value (read-only copy), and `y` is captured by reference. | | `[&]` | All external variables used in the body are implicitly captured by reference. | | `` | All external variables used in the body are implicitly captured by value. | | `[&, x]` | `x` is explicitly captured by value. All other used variables are captured by reference. | | `[=, &z]` | `z` is explicitly captured by reference. All other used variables are captured by value. | ### Capturing the `this` Pointer When using lambdas inside class member functions, you can capture the `this` pointer to access member variables and functions of the class. * With implicit captures like `` or `[&]`, `this` is captured automatically. * With an empty capture `[]`, you must pass `this` explicitly: ```cpp () { this->someMemberFunction(); }(); ```
← Cpp NumbersCpp Decision β†’