Functions can be called in two ways:-

1)Call by reference
2)Call by value

1)Call by value
Call by value is just calling a function simply.Call by value simply copies the values of the arguments in the formal parameters.For eg.

#include <iostream.h>

int ADD(int m);

int main(void)

{

int n= 50;

cout<<"%d %d"<< ADD (n), n);

return 0;
}

int ADD (int n)
{

n = n + n;

return n;
}

2)Call by refrence

Whenever you declare a variable in a program, the compiler reserves an amount of space for this variable. If you want to utilize that variable anywhere in your program, you call it thereby making use of its value. There are basically two biggest issues related to a variable: its value and its location in the memory.
The location of a variable in memory is referred to as its address.

If you supply the argument using its name, the compiler merely makes a backup of the argument’s value and provides it to the calling function. Although the calling function obtains the argument’s value and can use by any means, it cannot (permanently) modify it. C++ enables a calling function to modify the value of a passed argument if you think it necessary. If you want the calling function to modify the value of a supplied argument and return the customized value, you should pass the argument utilizing its reference.

To pass an argument as a reference, while declaring the function, precede the argument name with an ampersand “&”. You can pass 0, one, or higher arguments as reference in the program or perhaps pass all arguments as reference. The decision as to which argument(s) should be passed by value or by reference is based on whether or not you would like the called function to change the argument and permanently modify its value.

SWAPPING OF TWO NUMBERS(CALL BY REFERENCE)


#include <stdio.h>

void swaping (int *a, int *b);

int main(void)
{

int a = 10, b = 20;
  
cout<<"Before swapping: %d %d\n"<< a<<b;

swaping (&a, &b);

cout<<" after swapping: %d %d\n"<< a<< b;

return 0;
}

void swaping(int *a, int *b)
{
int temp;
temp = *a; /* save the value at address a */

*a = *b; /* put b into a */

*b = temp; /* put a into b */
}


0 comments to "PARAMETER PASSING IN FUNCTIONS"

Post a Comment

Powered by Blogger.