Home >Backend Development >C++ >How Do I Modify Original Variables When Passing Parameters to a C Function?
Passing Parameters by Reference vs. Value in a Function
Consider the following code snippet:
void trans(double x, double y, double theta, double m, double n) { m = cos(theta) * x + sin(theta) * y; n = -sin(theta) * x + cos(theta) * y; }
If you call this function as follows:
trans(center_x, center_y, angle, xc, yc);
and expect the values of xc and yc to change, you will be disappointed. This is because parameters are passed by value in C by default, meaning that any changes made to the parameters inside the function are not reflected in the original variables passed in.
To overcome this issue, you can either pass the parameters by reference or use pointer arithmetic.
Using References
In C , you can use references to pass parameters by reference. This allows you to modify the original variables passed in. Here's how you would modify the trans function to use references:
void trans(double x, double y, double theta, double& m, double& n) { m = cos(theta) * x + sin(theta) * y; n = -sin(theta) * x + cos(theta) * y; }
Note that the parameter types are now references to double (i.e., double&).
You can then call the function as follows:
trans(center_x, center_y, angle, xc, yc);
This will now correctly modify the values of xc and yc.
Using Pointer Arithmetic
Another way to pass parameters by reference in C is to use pointer arithmetic. This is more common in C, but it can also be used in C . Here's how you would modify the trans function to use pointer arithmetic:
void trans(double x, double y, double theta, double* m, double* n) { *m = cos(theta) * x + sin(theta) * y; *n = -sin(theta) * x + cos(theta) * y; }
Note that the parameter types are now pointers to double (i.e., double*).
You can then call the function as follows:
trans(center_x, center_y, angle, &xc, &yc);
This will also correctly modify the values of xc and yc.
The above is the detailed content of How Do I Modify Original Variables When Passing Parameters to a C Function?. For more information, please follow other related articles on the PHP Chinese website!