Complete Guide to Functions in C++
1. Introduction to Functions in C++
Functions in C++ allow you to break a program into smaller, reusable parts. They enhance readability, reduce
repetition, and help modularize logic.
This guide includes all types of functions, advanced concepts, and full working code examples.
2. Basic Function Syntax
return_type function_name(parameter_list) {
// body of function
return value; // if applicable
}
3. Categories of Functions
1. Built-in Functions (e.g., cout, cin, sqrt)
2. User-defined Functions:
- No return, no parameters
- No return, with parameters
- With return, no parameters
- With return, with parameters
3. Inline Functions
4. Recursive Functions
5. Overloaded Functions
6. Functions with Default Parameters
7. Function Prototypes
8. Lambda Functions
4.1 Function with No Return and No Parameters
#include <iostream>
using namespace std;
void greet() {
cout << "Welcome to C++!" << endl;
}
int main() {
greet();
Complete Guide to Functions in C++
return 0;
}
4.2 Function with Parameters and No Return
#include <iostream>
using namespace std;
void displaySum(int a, int b) {
cout << "Sum: " << a + b << endl;
}
int main() {
displaySum(10, 20);
return 0;
}
4.3 Function with Return and Parameters
#include <iostream>
using namespace std;
int multiply(int a, int b) {
return a * b;
}
int main() {
int result = multiply(5, 6);
cout << "Product: " << result << endl;
return 0;
}
4.4 Recursive Function
#include <iostream>
using namespace std;
int factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
int main() {
cout << "Factorial of 5 is " << factorial(5) << endl;
return 0;
}
4.5 Inline Function
Complete Guide to Functions in C++
#include <iostream>
using namespace std;
inline int square(int x) {
return x * x;
}
int main() {
cout << "Square of 4 is " << square(4) << endl;
return 0;
}
4.6 Function Overloading
#include <iostream>
using namespace std;
int add(int a, int b) {
return a + b;
}
float add(float a, float b) {
return a + b;
}
int main() {
cout << add(3, 4) << endl;
cout << add(3.5f, 2.5f) << endl;
return 0;
}
4.7 Function with Default Arguments
#include <iostream>
using namespace std;
void greet(string name = "Guest") {
cout << "Hello, " << name << "!" << endl;
}
int main() {
greet("Alice");
greet();
return 0;
}
4.8 Function Prototype
#include <iostream>
Complete Guide to Functions in C++
using namespace std;
int sum(int, int); // prototype
int main() {
cout << "Sum is: " << sum(4, 5) << endl;
return 0;
}
int sum(int a, int b) {
return a + b;
}
4.9 Lambda Function
#include <iostream>
using namespace std;
int main() {
auto add = [](int x, int y) { return x + y; };
cout << "Sum: " << add(5, 6) << endl;
return 0;
}
5. Conclusion
Functions in C++ are powerful tools that help you write modular, efficient, and maintainable code. By
mastering all function types, including recursion, overloading, and lambda expressions, you can significantly
enhance your C++ programming skills.