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:

Picture 1 of Call the function by reference in C ++

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 ++

Update 25 May 2019
Category

System

Mac OS X

Hardware

Game

Tech info

Technology

Science

Life

Application

Electric

Program

Mobile