### Pointer rewrite

need help with pointer homework my return statement isnt working and i cant find in my textbook a good example on how to do it.

Problem is: the following function uses reference variables as parameters. rewrite the function so it uses pointers instead of reference variables and then demonstrate the function in a complete program

int doSomething(int &x, int &y)
{
int temp =x;
x = y *10;
y = temp * 10;
return x + y;
}

now my code is:

int doSomething(int *x, int *y)
{

int temp=*x;
*x= *y * 10;
*y = temp * 10;
return x+y;
}

int main()
{
int y,z;
cout << "Please enter a number" << endl;
cin >> y;
cout << "Please enter another number" << endl;
cin >> z;

doSomething(&y, &z);
system("Pause");
return 0;
}

Change the last statement of the function the following way

int doSomething(int *x, int *y)
{

int temp=*x;
*x= *y * 10;
*y = temp * 10;
return *x+*y;
}
sweet it worked thank you
To demonstrate the function add the following statement to the main instead of the statement

doSomething(&y, &z);

std::cput << doSomething(&y, &z) << " = x(" << x << ") + y(" << y << ")'n";

or something similar
Last edited on
@vlad: how could that happened? i tested it, the code is:
 ``123456789101112131415161718192021222324252627`` ``````#include using namespace std; int doSomething(int *x, int *y) { int temp=*x; *x= *y * 10; *y = temp * 10; return *x+*y; } int main() { int y,z; cout << "Please enter a number" << endl; cin >> y; cout << "Please enter another number" << endl; cin >> z; doSomething(&y, &z); cout << doSomething(&y, &z) << " = y(" << y << ") + z(" << z << ")'n" << endl; system("Pause"); return 0; }``````

result is:
 Please enter a number 7 Please enter another number 3 1000 = y(30) + z(70)'n Press any key to continue . . .

but, if i change the code:
 ``123456789101112131415161718192021222324252627`` ``````#include using namespace std; int doSomething(int *x, int *y) { int temp=*x; *x= *y * 10; *y = temp * 10; return *x+*y; } int main() { int y,z; cout << "Please enter a number" << endl; cin >> y; cout << "Please enter another number" << endl; cin >> z; doSomething(&y, &z); doSomething(&y, &z); cout << (y + z) << " = y(" << y << ") + z(" << z << ")'n" << endl; system("Pause"); return 0; }``````

result is:
 Please enter a number 4 Please enter another number 9 1300 = y(400) + z(900)'n Press any key to continue . . .

why?
First of all there is a typo in this statement

cout << (y + z) << " = y(" << y << ") + z(" << z << ")'n" << endl;

Shall be

cout << (y + z) << " = y(" << y << ") + z(" << z << ")\n" << endl;

or remove \n from the last string literal.

In the first case the order of evaluation of function arguments (arguments of operator << ) is undefined. So as arguments are usually evaluates from right to left x and y have values before calling doSomething the second time.
Topic archived. No new replies allowed.