C/C++ Why Isn't My C++ Function Passing By Reference Correctly?

AI Thread Summary
The discussion focuses on defining a function, CoordTransform(), that transforms two input parameters, xVal and yVal, into new output parameters, xValNew and yValNew, using the formula new = (old + 1) * 2. A user initially implemented the function but encountered an issue where the output values remained unchanged, resulting in (3, 4) becoming (0, 0) instead of the expected (8, 10). The problem was identified as a variable scope issue; the function was not modifying the original variables because they were passed by value. The solution involved changing the function signature to pass xValNew and yValNew by reference using the "&" operator, allowing the function to directly modify the original variables. This adjustment resolved the issue, enabling the function to produce the correct output.
Colton0117
Messages
5
Reaction score
0
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.

My code:

Code:
#include <iostream>
using namespace std;

void CoordTransform(int xVal , int yVal , int xValNew, int yValNew){ 
    
   xValNew = (xVal +1) *2;
   yValNew = (yVal +1) *2;  
   return;
}

int main() {
   int xValNew = 0;
   int yValNew = 0;

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

   return 0;
}

My output is (3, 4) becomes (0, 0) when it should be (8, 10), what am I missing or overlooking to operate the void and have x or y ValNew hold its value?
 
Technology news on Phys.org
It looks like an issue of variable scope. The values you are passing to your function are then local to the function. You may need to either make the variables containing the new values global, or return them explicitly. :)
 
Thanks, the issue was the void it should be:

void CoordTransform(int x ,int y ,int& xValNew,int& yValNew)

needed the & after the int
 
Colton0117 said:
Thanks, the issue was the void it should be:

void CoordTransform(int x ,int y ,int& xValNew,int& yValNew)

needed the & after the int

Yes, basically the "&" says "don't make a copy of this variable, use the same variable." :)
 
Thread 'Is this public key encryption?'
I've tried to intuit public key encryption but never quite managed. But this seems to wrap it up in a bow. This seems to be a very elegant way of transmitting a message publicly that only the sender and receiver can decipher. Is this how PKE works? No, it cant be. In the above case, the requester knows the target's "secret" key - because they have his ID, and therefore knows his birthdate.

Similar threads

Replies
1
Views
1K
Replies
39
Views
4K
Replies
5
Views
3K
Replies
6
Views
1K
Replies
25
Views
2K
Replies
19
Views
5K
Back
Top