The arguments passed to a function can be performed in two ways:
- Passed By Value
- Passed By Reference
Passed By Value:
In the earlier chapter, all examples for the function with arguments were passed by value. Arguments passed by value are the copies of the values of variables and are passed to the function. The variables defined in the calling function are not passed in this manner.
For example:
|
would pass values as
|
Passed By Reference:
Passed by reference indicates a contrast in that the variables are not passed by value. When a variable is passed by reference, it passes the variable to the function definition and not the copies of the value. Any changes to the variable in function definition would effect or reflect corresponding changes in the variables passed as reference.
The symbol used for denoting the passed by reference is & (ampersand).For Example:
Suppose two integer variables x and y are defined in the calling function, the main program with values x=5 and y=4.Suppose the function exforsys receives the value as passed by reference from this function it is defined and called as follows:
|
In the above example, the reference arguments are indicated by the symbol ampersand & following the data type of the argument. In the above program, since the variables or arguments are passed by reference the assignment is as follows:
void exforsys(int& s, int& u)
exforsys(x, y);
The variable x and y are passed to the called function exforsys where it is associated with variables s and u. Whatever changes were made in the variable s and u effect or reflect on the variables x and y respectively and vice versa. Only in the above, the function multiplied the value of variable s and u by 10 which is reflected in the variable a and b. Thus, in this case, it has not returned any value by using return statement. The programmer must take careful notice and make use of the passed by reference concept by returning more than one value. By using the concept of passing by reference, it is possible to return more than one value.
The output of the above program would beThe output from Calling program is:
x=50
y=40
No comments:
Post a Comment