Nihat Yildirim Nihat Yildirim - 25 days ago 14
C++ Question

Returning void function

Im pretty new here. Hopefully, I will be able to contribute over time. Im having a trouble to have this new values assigned. Whenever I run the code, they get only zeros.

#include <iostream>
using namespace std;


void CoordTransform(int xVal,int yVal,int xValNew, int yValNew) {


xValNew = (xVal + 1) * 2;
yValNew = (yVal + 1) * 2;

return void();
}


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

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

return 0;
}

Answer

Passing arguments as you have is passing "by value". Changing the value in the function has no affect on the original variable holding the value that was passed to the function.

Pass by reference instead. The reference is to the original variable, so changing the parameter in the function changes the original variable.

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

Additionally, a void return value means you don't return anything directly from the function. Don't use a return statement.

Comments