Call by Reference - NayiPathshala

Breaking

Total Pageviews

Loading...

Search Here

1/05/2018

Call by Reference

Call by Reference 

The call by reference method of passing arguments to a function copies the reference of an argument into the formal parameter. Inside the function, the reference is used to access the actual argument used in the call. This means that changes made to the parameter affect the passed argument. To pass the value by reference, argument reference is passed to the functions just like any other value. So accordingly you need to declare the function parameters as reference types as in the following function swap(), which exchanges the values of the two integer variables pointed to by its arguments


For now, let us call the function swap() by passing values by reference as in the following example:



 When the above code is put together in a file, compiled and executed, it produces the following result:



By default, C++ uses call by value to pass arguments. In general, this means that code within a function cannot alter the arguments used to call the function and above mentioned example while calling max() function used the same method.

 Default Values for Parameters

When you define a function, you can specify a default value for each of the last parameters. This value will be used if the corresponding argument is left blank when calling to the function. C++
 This is done by using the assignment operator and assigning values for the arguments in the function definition. If a value for that parameter is not passed when the function is called, the default given value is used, but if a value is specified, this default value is ignored and the passed value is used instead. Consider the following example:




When the above code is compiled and executed, it produces the following result:


No comments:

Post a Comment