Function in C++
We will learn about the functions in C++. How to declare a function, call functions, function perimeters, and function prototype.
A function is a block of code that performs a specific task on call.
For example, we need to add or multiple two variables. Then we have to create two functions.
- Function to add two variables
- Function to multiple two variable
Here a question arise why we need these function?
The major need of function is to divide a complex problem into smaller parts and makes our program easy to understand and reusable.
There two types of functions.
- Standard Library function (predefined in C++)
- User-defined Function ( created by users)
In this post, we will focus on User-defined Function.
User-defined Function in C++
In C++, a programmer can define their own function.
A user-defined function groups code to perform a specific task and that group of code is given a name (identifier).
When the function is invoked from any part of the program, it all executes the codes defined in the body of the function.
Function Declaration in C++
The syntax to declare a function is:
ReturnType FunctionName(Parameter1, Parameter2, Parameter3,.....){// Function Body}
Example of Function Declaration
Void Future(){cout << " Hello Future " << endl;}
- Name of Function is Future
- Return type is Void
- No Parameters is passes in this function.
- Body of function is written in between {} brackets.
Calling a Function
In the above program, we have declared a function named Future(). To use the Future() function, we need to call it.
Get Shazibbilal’s stories in your inbox
Join Medium for free to get updates from this writer.
Here’s how we can call the above Future() function.
int main(){Future()}
Example 01: Display some text by using a function
#include<iostream>using namespace std;// Declaring the functionsvoid Display(){cout << " Hello programming World " << endl;}int main(){calling functionDisplay();}
Output:
Hello programming WorldFunction Parameters
If some values have to pass the function then function have to declare with some parameters.
For example, let us consider the function below:
Here, the int variables a and b are the function parameter.
void Sum(int a, int b){cout << " sum is " << a + b << endl;}
We have to pass the values to the function parameter while calling the function.
int main() {int a= 10, b = 30;// calling the function// a and b are passes to the function as an argumaentSum(a,b);return 0;}
Originally published at https://www.pcslearning.com on October 2, 2022.





