C and C++ function parameter transfer mechanism details and examples

  • 2020-05-17 05:57:49
  • OfStack

Details and examples of C/C++ function parameter transfer mechanism

Summary:

There are two basic parameter passing mechanisms for C/C++ : value passing and reference passing. Let's take a look at the differences between the two.

(1) in the process of value transfer, it is necessary to create a memory space in the stack to store the value of arguments put in by the main call function, thus becoming a copy of arguments. The characteristic of value transfer is that any operation of the tunable function on the parameter is carried out as a local variable and does not affect the value of the real parameter of the main tunable function.

(2) in the process of reference passing, the parameter of the function to be called, although it is also used as a local variable to open up a memory space in the stack, is stored at this time is the address of the real parameter put in by the main function. Any operation of the called function on the formal parameters is treated as indirection, that is, access to the real variables in the main function through the address stored on the stack. Because of this, any operation the called function does to the parameter affects the real parameter in the main function.

Let's look at an example.


/*
* Test the function parameter passing mechanism 
*/
class CRect {

public:
  int height;
  int widht;

  CRect() {
    height = 0;
    widht = 0;
  }

  CRect(int height, int widht) {
    this->height = height;
    this->widht = widht;
  }

};

// ( 1 ) address call (pointer) 
int RectAreaPoint(CRect *rect) {
  int result = rect->height * rect->widht;
  rect->height = 20;
  return result;
}

// ( 2 ) reference passing 
int RectAreaRefer(CRect &rect) {
  int result = rect.height * rect.widht;
  rect.height = 30;
  return result;

}

// ( 3 ) 
int RectArea(CRect rect) {
  int result = rect.height * rect.widht;
  rect.height = 40;
  return result;
}

Take a look at our test code and test results.


// Test code logic 
void testPoint() {
  CRect rect(10, 10);
  cout << " Area: " << RectAreaPoint(&rect) << endl;
  cout << " Area: " << RectAreaRefer(rect) << endl;
  cout << "rect.height : " << rect.height << endl;
  cout << " Area: " << RectArea(rect) << endl;
  cout << "rect.height : " << rect.height << endl;
}

// The test results 
 Area: 100
 Area: 200
rect.height : 30
 Area: 300
rect.height : 30

It can be found that both address call and reference pass, when changing the value of the parameter, will also change the value of the argument, while the value transfer call changes the parameter without any effect on the argument.

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: