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