Electron microscopy
 
Reference Parameters in C++ and DM
- Practical Electron Microscopy and Database -
- An Online Book -
Microanalysis | EM Book                                                                                   http://www.globalsino.com/EM/        


=================================================================================

 

In argument passing in C++ as well as DM, it is possible to tell the compiler to automatically use call-by-reference rather than call-by-value for one or more parameters of a particular function with a reference parameter. When a reference parameter is used, the address (not the value) of an argument is automatically passed to the function. Within the function, operations on the reference parameter are automatically de-referenced. If an argument is passed by a reference, then an "&" character is placed before the variable name in the parameter list in the function definition. That is, a reference parameter is declared by preceding the parameter name in the function's declaration with an &. Operations performed on a reference parameter affect the argument which is used to call the function, not the reference parameter itself. When a reference parameter is used, the C++ compiler automatically knows that it is an address and de-references it.

Table 1122. Examples of applications of reference parameters.

Script Note
applications of reference parameters
Script file

This program displays the following output:
         Old value for EMvalue: 1
         New value for EMvalue: 10

Function EMfunc( ) takes one reference parameter of type "number"

EMi is preceded by an &, which causes it to become a
reference parameter

Since EMi has been declared as a reference parameter, the compiler will automatically pass EMfunc( ) the address of any argument it is called with. Therefore, Line 14 passes the address of EMvalue (but not its value) to EMfunc( ). There is no need to precede EMvalue with the & operator.

Since EMfunc( ) receives the address of EMvalue in the form of a reference, it may modify the value of EMvalue.

"EMvalue = 1" in Line 12 does not cause EMi to be given the value 10. Instead, it causes the variable referenced by EMi (EMvalue) to be assigned the value 10.

 

 

 

=================================================================================