Call the function by value in C ++

The method calls the function by the value of the parameters passed to a function that copies the actual value of a parameter into the official argument of the function. In this case, changes made to the parameter inside the function have no effect on the parameter.

The method calls the function by the value of the parameters passed to a function that copies the actual value of a parameter into the official argument of the function. In this case, changes made to the parameter inside the function have no effect on the parameter.

By default, C ++ Language uses the call function by value to pass parameters. Under the general sense, the code inside a function cannot change the parameter used to call the function. Suppose the definition of the function traodoi () is as follows:

 // phan dinh nghia ham de trao doi cac gia tri. void traodoi ( int x , int y ) { int temp ; temp = x ; /* luu giu gia tri cua x */ x = y ; /* dat y vao trong x */ y = temp ; /* dat x vao trong y */ return ; } 

Now we call the function traodoi () by passing true values ​​like 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 de trao doi cac gia tri. 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 value in C ++ Picture 1Call the function by value in C ++ Picture 1

It indicates that there is no change in value even though they have been changed inside the function.

According to Tutorialspoint

Previous article: Function in C / C ++

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

4 ★ | 1 Vote