Functions – Complete Tutorial
1. What is a Function?
A function is a block of code that performs a specific task. Functions help in code reuse, modularity, and readability.
2. Function Declaration and Definition
Function Declaration
A function declaration tells the compiler about the function name, return type, and parameters.
Syntax:
Example:
Function Definition
A function definition contains the actual implementation.
Example:
3. Function Call
A function is executed when it is called.
Example:
4. Return Types
The return type specifies the type of value a function returns.
Common Return Types:
intfloatdoublecharvoid
Example:
Best Practices:
- Use meaningful return types
- Avoid using global variables instead of return values
5. Function Overloading
Function overloading allows multiple functions with the same name but different parameter lists.
Example:
Rules:
- Different number of parameters or
- Different types of parameters
- Return type alone cannot differentiate functions
6. Inline Functions
Inline functions reduce function call overhead by replacing the function call with the function body.
Syntax:
Best Practices:
- Use inline for small functions
- Avoid inline for complex or recursive functions
7. Call by Value
In call by value, a copy of the actual parameter is passed to the function.
Example:
8. Call by Reference
In call by reference, the function receives a reference to the actual parameter.
Example:
Advantages:
- No extra memory used
- Faster execution
- Used to modify original values
Call by Value vs Call by Reference
| FeatureCall by ValueCall by Reference | ||
| Data copied | Yes | No |
| Memory usage | More | Less |
| Original value modified | No | Yes |
Best Practices for Functions
- Keep functions small and focused
- Use meaningful function names
- Avoid side effects
- Prefer passing by reference for large objects
- Use
constreference when modification is not required
Common Mistakes to Avoid
- Mismatched function declaration and definition
- Overusing inline functions
- Confusing overloading with overriding
- Passing large objects by value unnecessarily
Summary
In this chapter, you learned about C++ functions, including declaration, definition, function calls, return types, function overloading, inline functions, and parameter passing techniques. Functions are essential for building modular and maintainable C++ programs.