Pointer Rewrite:
The following function uses reference variables as parameters. Rewrite the function so it uses pointers instead of reference variables, 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;
}
check out the solution.
-----------------------------------
CODE:
#include<stdio.h>
// rewriting the function using pointers
int doSomething(int *x, int *y)
{
// declare a pointer
int *temp;
temp = x; // assign address of x to temp so now temp is pointing to
x value
*x = *y * 10; // now x = 20*10 = 200 -> x points to 200
value
*y = *temp * 10; // as temp points to x value so 'temp = 200' =>
y = 200*10 = 2000
// return the result using pointers
return *x + *y; // x = 200 and y = 2000 => returns 200+2000 =
2200.
}
int main()
{
// variables declaration
int a, b, result;
// variable assignment
a = 10;
b = 20;
// function call by passing the variable references
result = doSomething(&a, &b);
// print the returned result
printf("Result = %d", result);
}
----------------------------------
--------------------------------------------
OUTPUT :
=======================================
Get Answers For Free
Most questions answered within 1 hours.