Lisa
Lisa

Reputation: 621

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

I have written a function below:

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 I call them in the same file by

trans(center_x,center_y,angle,xc,yc);

will the value of xc and yc change? If not, what should I do?

Upvotes: 22

Views: 56581

Answers (4)

C. K. Young
C. K. Young

Reputation: 223123

Passing by reference is indeed a correct answer, however, C++ sort-of allows multi-values returns using std::tuple and (for two values) std::pair:

#include <cmath>
#include <tuple>

using std::cos; using std::sin;
using std::make_tuple; using std::tuple;

tuple<double, double> trans(double x, double y, double theta)
{
    double m = cos(theta)*x + sin(theta)*y;
    double n = -sin(theta)*x + cos(theta)*y;
    return make_tuple(m, n);
}

This way, you don't have to use out-parameters at all.

On the caller side, you can use std::tie to unpack the tuple into other variables:

using std::tie;

double xc, yc;
tie(xc, yc) = trans(1, 1, M_PI);
// Use xc and yc from here on

Hope this helps!

Upvotes: 10

Mark Rushakoff
Mark Rushakoff

Reputation: 258358

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.

Upvotes: 49

timB33
timB33

Reputation: 1987

as said above, you need to pass by reference to return altered values of 'm' and 'n', but... consider passing everything by reference and using const for the params you don't want to be altered inside your function i.e.

void trans(const double& x, const double& y,const double& theta, double& m,double& n)

Upvotes: 0

Soufiane Hassou
Soufiane Hassou

Reputation: 17750

You need to pass your variables by reference which means

void trans(double x,double y,double theta,double &m,double &n) { ... }

Upvotes: 1

Related Questions