What is the use of & (ampersand) in the given function

Define a function CoordTransform() that transforms its first two input parameters xVal and yVal into two output parameters xValNew and yValNew. The function returns void. The transformation is new = (old + 1) * 2. Ex: If xVal = 3 and yVal = 4, then xValNew is 8 and yValNew is 10.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
  void CoordTransform(int xVal, int yVal, int &xValNew, int &yValNew){
	//new = (old +1) * 2
	xValNew = (xVal + 1) * 2;
	yValNew = (yVal + 1) * 2;
}
int main() {
   int xValNew = 0;
   int yValNew = 0;

   CoordTransform(3, 4, xValNew, yValNew);
   cout << "(3, 4) becomes " << "(" << xValNew << ", " << yValNew << ")" << endl;

   return 0;
}


Can anyone please explain the use of & (ampersand)
Hello philip1999,

Welcome to the forum.

In his case in the function parameters it is saying the t the variable "xValueNwe" and "yValueNew" are being passed by reference. That means tat any change to these variables will be reflected in main. It gives you the ability to pass and use a variable passed to a function and make changes to it that are reflected back in the calling location. That is why the "cout" statement in main shows the changes.

You will notice that the first two parameters do not have the "&". These variables are being passed by value. You can also think of these variables as copies of the original variable or number passed from main. You can make changes to these copies, but they are only local variables and lost when the function ends.

Hope that helps,

Andy
Slow down Andy, you get typing too fast there.

@philip
To see the affect the '&' makes, simple remove it and notice the difference.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
  #include <iostream>
  using namespace std;
  
  void CoordTransform(int xVal, int yVal, int xValNew, int yValNew){
	//new = (old +1) * 2
	xValNew = (xVal + 1) * 2;
	yValNew = (yVal + 1) * 2;
}
int main() {
   int xValNew = 0;
   int yValNew = 0;

   CoordTransform(3, 4, xValNew, yValNew);
   cout << "(3, 4) becomes " << "(" << xValNew << ", " << yValNew << ")" << endl;

   return 0;
}
Last edited on
closed account (E0p9LyTq)
What is the use of & (ampersand) in the given function

Do you understand what a pointer is? And what it can do?

A study of references (and pointers) would be in order:
https://www.tutorialspoint.com/cplusplus/cpp_references.htm

More to your question:
https://www.tutorialspoint.com/cplusplus/passing_parameters_by_references.htm

When to pass parameters by value, reference, and pointer
http://www.cplusplus.com/articles/z6vU7k9E/
Last edited on
Topic archived. No new replies allowed.