Home >Backend Development >C++ >How Do I Modify Original Variables When Passing Parameters to a C Function?

How Do I Modify Original Variables When Passing Parameters to a C Function?

DDD
DDDOriginal
2024-12-27 04:28:28396browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn