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.
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 should read it
- PHP functions
- 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
- Call the function by pointer in C ++
- Call the function by value in C ++
- Reference in C ++
- Load the operator stack to call the function () in C ++
- Anonymous method in C #
- INDIRECT function in Excel - How to use INDIRECT function and examples using INDIRECT function
- The OFFSET function returns a reference in Excel
- How to use Lookup function in Excel
- Offset function in Excel - Usage and examples
Maybe you are interested
How to Integrate ChatGPT for Siri on iPhone
How to get data from web into Excel
Top best apps to turn men into women, boys into girls
How to blur background images in PowerPoint - Adjust background image display mode
Instructions for creating PowerPoint background color effects - Create a new background for slides
7 Best Pinterest Alternatives