When I change a parameter inside a function, does it change for the caller, too?

Since you’re using C++, if you want xc and yc to change, you can 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;
}

int main()
{
    // ... 
    // no special decoration required for xc and yc when using references
    trans(center_x, center_y, angle, xc, yc);
    // ...
}

Whereas if you were using C, you would have to pass explicit pointers or addresses, such as:

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;
}

int main()
{
    /* ... */
    /* have to use an ampersand to explicitly pass address */
    trans(center_x, center_y, angle, &xc, &yc);
    /* ... */
}

I would recommend checking out the C++ FAQ Lite’s entry on references for some more information on how to use references properly.

Leave a Comment