Professional Documents
Culture Documents
the complex code. For that reason, We use function to place independent code in separate
modules called function or subprogram. In order to make a program using function, we need to
perform the followling three steps.
Function declaration
Function definition
Function call
Function declaration
Like variables, all the functions must be declared. Function declaration statement includes
function name, what function will take and what function will return.
Syntax :
argument list : represents the type and number of value function will take, values are sent by
the calling statement.
Function definition
Function definition includes the actual working or implementation.
The body of function contains the number of statements to perform specific task.
sum = x + y;
return sum;
}
var = function-name(val1,val2...n);
var can be any variable that will recieve value returning from function definition.
Call by Value
Call by Reference/Address
Call by Value
In this approach, the values are passed as function argument to the definition of function.
#include<iostream.h>
void main()
{
int A=10,B=20;
fun(A,B); //Statement 1
Output :
In the above example, statement 1 is passing the values of A and B to the calling function
fun(). fun() will recieve the value of A and B and put it into X and Y respectively. X and Y are
value type variables and are local to fun(). Any changes made by value type variables X and Y
will not effect the values of A and B.
Call by Reference
In this approach, the references/addresses are passed as function argument to the definition
of function.
#include<iostream.h>
void main()
{
int A=10,B=20;
fun(&A,&B); //Statement 1
}
void fun(int *X,int *Y) //Statement 2
{
*X=11;
*Y=22;
}
Output :
In the above example, statement 1 is passing the reference of A and B to the calling function
fun(). fun() must have pointer formal arguments to recieve the reference of A and B. In
statement 2 *X and *Y is recieving the reference A and B. *X and *Y are reference type
variables and are local to fun(). Any changes made by reference type variables *X and *Y will
change the values of A and B respectively.
The values of actual argument are The reference of actual argument are
sent to formal argument which are sent to formal argument which are
normal variables. pointer variables.
http://www.tutorialdost.com/Cpp-Programming-
Tutorial/17-Cpp-Functions.aspx