Call the function by reference in C ++
The method of calling a function by reference of parameters passed to a function copies the address of a parameter into the official parameter. Within that function, the address used to access the parameter is actually used in calling the function. This means that changes are made with parameters that affect the passed parameters.
The method of calling a function by reference of parameters passed to a function copies the address of a parameter into the official parameter. Within that function, the address used to access the parameter is actually used in calling the function. This means that changes are made with parameters that affect the passed parameters.
To pass values by reference, parameter pointers are passed to functions like any other value. Therefore, you need to declare the function parameters as pointer types as in the traodoi () function as follows, but change the value of the two integer variables pointed to by its parameters.
// phan dinh nghia ham de trao doi cac gia tri. void traodoi ( int & x , int & y ) { int temp ; temp = x ; /* luu giu gia tri tai dia chi x */ x = y ; /* dat y vao trong x */ y = temp ; /* dat x vao trong y */ return ; }
Now, we call the function traodoi () by passing the values by reference as follows:
#include using namespace std ; // phan khai bao ham void traodoi ( int & x , int & y ); int main () { // Khai bao bien cuc bo: int a = 100 ; int b = 200 ; cout << "Truoc khi trao doi, gia tri cua a la: " << a << endl ; cout << "Truoc khi trao doi, gia tri cua b la: " << b << endl ; /* goi ham traodoi de trao doi cac gia tri boi su dung tham chieu bien.*/ traodoi ( a , b ); cout << "Sau khi trao doi, gia tri cua a la: " << a << endl ; cout << "Sau khi trao doi, gia tri cua b la: " << b << endl ; return 0 ; }
You put the above function definition at the end of this code, then compile and run the above C ++ program will produce the following result:
This indicates that the changes reflect outside the function, unlike the function by the value that the changes do not reflect outside the function.
According to Tutorialspoint
Last lesson: Call the function by pointer in C ++
Next lesson: Number in C ++
You've just finished reading the article "Call the function by reference in C ++" edited by the TipsMake team. You can save call-the-function-by-reference-in-c-.pdf to your computer here to read later or print it out. We hope this article has provided you with many useful tech tips and tricks. You can search for similar articles on tips and guides. Thank you for reading and for following us regularly.
- Load the operator stack to call the function () in C ++
- Call the function by value in C ++
- SHEETS function - The function returns the number of pages in a reference in Excel
- ISREF function - The function returns True if the value is a valid reference value in Excel
- Reference in C ++
- The Index function in Excel: Formulas and usage.