Functions are the building blocks of efficient and modular programming in C++. They enable developers to perform specific tasks, improve code readability, and reuse logic across programs. A function is defined with a return type, name, and optional parameters, making it easy to encapsulate and reuse logic.
In C++, functions can be categorized as built-in functions, such as cout
and sqrt
, and user-defined functions, which are written by programmers to address specific needs. Key components of functions include declarations, definitions, and calls, each contributing to a seamless flow in program execution.
Whether you’re working with void functions, inline functions, or recursive calls, understanding their structure and types can greatly enhance the readability, reusability, and maintainability of your code.
–Doing specific task.
–They help in modularizing code,
–improving readability,
-reusing logic across the program.
return_type function_name(parameters) {
// Function body
return value;
}
#include <iostream>
using namespace std;
// User-defined function
int add(int a, int b) {
return a + b;
}
int main() {
int a1= 20, b1 = 30;
cout << “Sum: ” << add(a1, b1) << endl; // Call the function
return 0;
}
int add(int a, int b);
int add(int a, int b) { return a + b;}
add(num1, num2);
#include <iostream>
using namespace std;
// User-defined function
int add(int a, int b) {
return a + b;
}
int main() {
int num1 = 10, num2 = 20;
cout << “Sum: ” << add(num1, num2) << endl; // Call the function
return 0;
}
1. Void Functions: Do not return any value.
void printMessage() {
cout << “Hello, World!” << endl;
}
2. Parameterized Functions: Accept parameters.
int multiply(int x, int y) { return x * y;}
3. Function with Default Arguments:
int sum(int a, int b = 5) { // b has a default value of 5
return a + b;
}
4. Inline Functions: Defined with the inline keyword for small, frequently used functions.
inline int square(int x) {
return x * x;
}
5. Recursive Functions: A function that calls itself.
int factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n – 1);
}
void increment(int &x) {
x++;
}
void increment(int *x) {
(*x)++;
}
Multiple functions can have the same name but different parameter lists.
#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(5, 10) << endl; // Calls int version
cout << add(5.5f, 10.5f) << endl; // Calls float version
return 0;
}
Indian Institute of Embedded Systems – IIES