Functions are the building blocks of a program, designed to perform specific tasks. They promote code reusability, enhance organization, and simplify debugging, making programs more efficient and easier to maintain.
A function typically consists of:
int
, void
).Whether it’s a simple addition, greeting message, or handling complex mathematical operations, functions form the foundation of clean, organized programming in C++. They can also be overloaded, enabling multiple implementations with the same name but varying parameters for greater flexibility.
Function(Doing specific Task):
Functions allow for code reusability,
better organization,
and easier debugging.
return_type function_name(parameter_list) {
// Function body: statements to execute
return return_value;
}
cpp
Copy code
#include <iostream>
using namespace std;
// Function declaration
int add(int a, int b);
int main() {
int result = add(5, 3);
cout << “The sum is: ” << result << endl; // Output the result
return 0;
}
// Function definition
int add(int a, int b) {
return a + b; // Returning the sum
}
Here:
int add(int a, int b) is the function declaration and definition.
The function add takes two integers as parameters and returns their sum.
cpp
Copy code
#include <iostream>
using namespace std;
// Function declaration
void greet();
int main() {
greet();
return 0;
}
// Function definition
void greet() {
cout << “Hello, world!” << endl;
}
Here:
void greet() is a function that doesn’t return any value.
The function simply prints a greeting message.
In C++, you can have multiple functions with the same name, but different parameter types or numbers. This is called function overloading.
#include <iostream>
using namespace std;
int multiply(int a, int b) {
return a * b;
}
double multiply(double a, double b) {
return a * b;
}
int main() {
cout << “Int multiplication: ” << multiply(2, 3) << endl;
cout << “Double multiplication: ” << multiply(2.5, 3.5) << endl;
return 0;
}
Must Read: STM32 ADC: Analog Sensor Reading
Indian Institute of Embedded Systems – IIES