What are functions in C and C++?
Functions in C and C++
As the name suggests, a function does some action; for example, when you switch ON the light bulb, that switch performs a particular action to turn on the Light Bulb. Similarly, Functions in programming are used to perform a specific task to save our time by writing the same logical code.
Why use a Function?
It is used where the repeated task has to be done. It also makes your code neat and simple to understand. Many professional programmers advise using Functions because it is the best practice for coding and debugging any error. You should also prefer to use functions in your program. It divides your code into simpler blocks and thus reduces redundancy.
Functions are of two types:
- Predefined Functions: These type of functions have been previously defined and they can be used by using Header files.For example, main() is a predefined, and compiler looks for it.
- User-Defined Functions: These type of function are defined by the User, and used later in the program.
Working of Function

Return Type: It tells us what data type a particular function will give. Examples, void, float, double, int, etc. Note that with the void, you cannot use return.
Function Name: It is the unique name of the function. If more than one same name is defined in a program, the compiler will throw an error message. It could be any name.
Argument Name and Type: It tells us what type of value a function will take and how many arguments are needed to be passed through it. There is no limit to the number of arguments.
Pass By Value: Here, the actual parameters are copied to the function’s formal parameters and the two types of parameters are stored in different memory locations. This ensures that any changes made inside the function are not changed in the actual parameters of the calling function.
Pass By Reference: Here, both are referred to the same address location; thus, any change made inside a function also changes the actual parameters of the calling function.
A simple example of Function :
Here a simple demonstration of function is given, along with an explanation in comments.
#include<iostream>
using namespace std;
int sum ( int a , int b ); // Function Declaration
int main()
{
int a , b ;
cout << "Enter 2 numbers " << endl;
cin >> a >> b;
int c = sum (a,b); // Function Calling with arguments passing
cout << "Sum of two numbers: "<< c;
return 0;
}
int sum ( int a , int b ) // Function Definition
{
return a + b;
}
Output
Enter 2 numbers
5 , 7
Sum of two numbers: 12