return_type | It is a data type that function returns. It is not necessary that function will always return a value. |
function_name | Function name is the actual name of the function. |
argument_list / parameters | It allows passing arguments to the function from the location where it is called from. The argument list is separated by comma. |
Function body | It contains a collection of statements that define what the function does. |
#include <iostream>
using namespace std;
int addition(int no1, int no2); //Function declaration
int main()
{
int num1=10, num2=20, result; //Local variable
result = addition(num1,num2); //Calling function. num1 & num2 are Actual Parameters
cout<<"Addition is : "<<result<<endl;
return 0;
}
int addition(int no1, int no2) //Function definition. no1 & no2 are Formal Parameters
{
int disp;
disp=no1+no2;
return disp;
}
Calculating the factorial of a number using recursive function.
#include <iostream>
using namespace std;
int factor (int);
int main()
{
int x = 5,fact;
fact = factor(x);
cout<<"Factorial is : "<<fact<<endl;
return 0;
}
int factor (int y)
{
int a;
if (y == 1)
return 1;
else
a = y*factor(y-1);
return (a);
}
Call by Value | Call by Reference |
---|---|
It is the method of passing arguments to a function that passes the actual value of an argument into the formal parameter of the function. | It is the method of passing arguments to a function that passes the reference of an argument into the formal parameter. |
Original value cannot be changed or modified in call by value. | Original value is changed or modified in call by reference. |
It passes value to the function. | It passes address of the value to the function. |
Actual and formal parameters will be created at different memory location. | Actual and formal parameters will be created at same location. |
In call by value, changes made to the parameter inside the function have no effect on the argument. | In call by reference, changes made to the parameter affect the argument, because address is used to access the actual argument. |
Example #include <iostream> using namespace std; void swap(int a, int b) { int temp; temp = a; a = b; b = temp; } int main() { int a = 10, b = 20; swap(a, b); //passing value to function cout<<"Value of a : "<<a<<endl; cout<<"Value of b : "<<b<<endl; return 0; } Output Value of a : 10 Value of b : 20 | Example #include <iostream> using namespace std; void swap(int *a, int *b) { int temp; temp = *a; *a = *b; *b = temp; } int main() { int a = 10, b = 20; swap(&a, &b); //passing value to function cout<<"Value of a : "<<a<<endl; cout<<"Value of b : "<<b<<endl; return 0; } Output Value of a : 20 Value of b : 10 |
#include <iostream>
using namespace std;
inline void display()
{
cout<<"Welcome to TutorialRide";
}
int main()
{
display(); // Call it like a normal function
}