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?

1

## 4 Answers

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.

1

if using c++, in the main should i call by trans(x, y, theta, &xc, &yc) or trans(x, y, theta, xc, yc);

–

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!

You need to pass your variables by reference which means

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

0

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)
```

Related questions: stackoverflow.com/questions/410593/pass-by-reference-value-in-c, stackoverflow.com/questions/1322517/…