C++ - Functions
Chapter 8: Functions
In this chapter, we will learn about functions in C++. Our learning will be based on the task based approach. Each task will help you to understand the requirements and then you will be able to implement the code.
1. Functions in C++ (Syntax, Return Type, etc.)
Notes:
-
A function is a block of code designed to perform a specific task.
-
Functions in C++ follow this basic syntax:
-
Return Type: Specifies the data type of the value returned by the function. Use
void
if no value is returned. -
Function Name: Describes what the function does.
-
Parameters: Input values for the function (optional).
Code Snippet:
2. Declaring a Function
Notes:
- Function declaration tells the compiler about the function’s name, return type, and parameters. It’s also called a function prototype.
- The function body is defined elsewhere.
Code Snippet:
3. Defining a Function
Notes:
- A function definition includes the full function with the body.
- You must define the function after declaring it if it’s not inline.
Code Snippet:
4. Calling a Function
Notes:
- To execute a function, you call it by its name followed by parentheses.
- If the function takes arguments, pass them inside the parentheses.
Code Snippet:
5. Function Parameters (Formal, Actual, Default Parameters)
Notes:
- Formal parameters: Defined in the function signature.
- Actual parameters: Values passed during the function call.
- Default parameters: Parameters with default values if none are passed.
Code Snippet:
6. Pass by Value
Notes:
- Pass by value means the function receives a copy of the argument. Changes made inside the function do not affect the original variable.
Code Snippet:
7. Pass by Reference
Notes:
- Pass by reference passes the actual variable, so changes in the function affect the original variable.
Code Snippet:
8. Scope of Variables
Notes:
- Variables declared inside a function have local scope (accessible only within the function).
- Variables declared outside all functions have global scope (accessible from any function).
Code Snippet:
9. Function Overloading
Notes:
- Function overloading allows multiple functions with the same name but different parameter types or numbers.
Code Snippet:
10. Lambda Functions
Notes:
- A lambda function is an anonymous function that can be defined inline using the
[]
syntax. - They’re useful for short, simple functions.
Code Snippet:
Summary:
- Function Declaration & Definition: Tell the compiler about a function and define what it does.
- Calling Functions: Execute the function by passing arguments if required.
- Pass by Value/Reference: Controls whether changes affect the original value or a copy.
- Function Overloading: Allows multiple functions with the same name but different parameter lists.
- Lambda Functions: Short, inline functions used for simple tasks.