30
60
The compiler selects the appropriate function based on the arguments.
10. Recursion
Recursion occurs when a function calls itself to solve a problem.
Every recursive function should have a base condition to stop further calls.
Example: Factorial using recursion
int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
}
return n * factorial(n - 1);
}
int main() {
cout << factorial(5);
return 0;
}Output:
120
Explanation:
factorial(5)
= 5 * factorial(4)
= 5 * 4 * factorial(3)
= 5 * 4 * 3 * factorial(2)
= 5 * 4 * 3 * 2 * factorial(1)
= 120
11. Inline Functions
An inline function suggests that the compiler replace a function call with the function's code where appropriate.
inline int square(int n) {
return n * n;
}
int main() {
cout << square(5);
return 0;
}Output:
25
The
inline keyword is a request to the compiler, not a guarantee that the function will be expanded inline.12. Lambda Functions
Lambda functions are anonymous functions that can be defined directly inside an expression.
They are useful when you need a small function without declaring a separate named function.
int main() {
auto greet = []() {
cout << "Hello from Lambda!";
};
greet();
return 0;
}Output:
Hello from Lambda!
Lambda with parameters:
auto add = [](int a, int b) {
return a + b;
};
cout << add(10, 20);Double Tap ❤️ For Part-4