Call the function by pointer in C ++

The method of calling a function by pointer in C ++ passes parameters to a function, copying the addresses of a parameter into the official parameter. Inside the function, this address is used to access the actual parameter used in the function call. That is, changes made to the official parameter affect the passed parameter.

The method of calling a function by pointer in C ++ passes parameters to a function, copying the addresses of a parameter into the official parameter. Inside the function, this address is used to access the actual parameter used in the function call. That is, changes made to the official parameter affect the passed parameter.

To pass values ​​by pointers, parameter pointers are passed to functions like any other value. Therefore, you need to declare the function parameters as a pointer type as in the following traodoi () function, which exchanges the values ​​of two integer variables pointed 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 ; } 

To check the details of the cursor in C ++, you access the chapter: Cursor in C ++.

Now, call the traodoi () function by passing the values ​​by the pointer as in the following example:

 #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 cua cac bien. * &a chi rang con tro dang tro toi a (dia chi cua bien a) va * &b chi rang con tro dang tro toi b (dia chi cua bien b). */ 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:

Call the function by pointer in C ++ Picture 1Call the function by pointer in C ++ Picture 1 Call the function by pointer in C ++ Picture 2Call the function by pointer in C ++ Picture 2

You should also follow the chapter: Call the function by value in C ++ to compare this difference.

According to Tutorialspoint

Previous lesson: Calling functions by value in C ++

Next lesson: Call the function by reference in C ++

5 ★ | 1 Vote