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.
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:
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 ++
You should read it
- Function realloc () in C
- Load the operator stack to call the function () in C ++
- Call the function by value in C ++
- Free () function in C
- Call the function by reference in C ++
- Python function parameter
- setjmp.h in C
- Returns the pointer from the function in C ++
- Callable () function in Python
- Malloc () function in C
- PHP functions
- How to create a quick reply to a call on iPhone
Maybe you are interested
6 ways to fix the error 'PowerPoint found a problem with the content'
Sample painting of Hanoi in my heart, simple landscape
PowerPoint 2016: Working with lists in PowerPoint
How to Paste an Image into a Selection in Photoshop
Europe develops satellite internet system to replace Starlink
Intel releases new driver update package with 6GHz optimization and many other improvements