Parameter Modification within Functions: Impact on the Caller
When modifying a parameter within a function, it's crucial to understand its effect on the caller. In the presented code snippet:
<br>void trans(double x,double y,double theta,double m,double n)<br>{</p> <div class="code" style="position:relative; padding:0px; margin:0px;"><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">m=cos(theta)*x+sin(theta)*y; n=-sin(theta)*x+cos(theta)*y;
}
calling this function with trans(center_x,center_y,angle,xc,yc) doesn't directly modify the values of xc and yc. This occurs because C passes function parameters by value, meaning the function receives a copy of the variables.
To address this, you have two options:
1. In C :
Use references to pass parameters by reference, modifying the original variables within the function:
<br>void trans(double x, double y, double theta, double& m, double& n)<br>{</p> <div class="code" style="position:relative; padding:0px; margin:0px;"><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">m=cos(theta)*x+sin(theta)*y; n=-sin(theta)*x+cos(theta)*y;
}
2. In C:
Pass parameters by explicitly passing their addresses using pointers:
<br>void trans(double x, double y, double theta, double<em> m, double</em> n)<br>{</p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">*m=cos(theta)*x+sin(theta)*y; *n=-sin(theta)*x+cos(theta)*y;
}
With these modifications, calling trans(center_x,center_y,angle,xc,yc) will directly update the values of xc and yc. If this behavior is desired, then using references or pointers is necessary to achieve the desired effect.
The above is the detailed content of How Do Parameter Modifications Inside a Function Affect the Calling Function in C and C ?. For more information, please follow other related articles on the PHP Chinese website!