2

Here's what I have:

#include <iostream>

using namespace std;

void test(double &r)
{
    r = 0.1;
}

int main() {
    double rdefined;
    double yo = test(&rdefined);
    cout << yo <<endl;
    return 0;
}

I've tried putting the test function after the main function and assigning rdefined as 0.0 .

3 Answers3

3

The function declaration void test(double &r) specifies that the argument is passed by reference not as a pointer. To pass a "pointer-to-double" use: void test(double *r).

Although, in practice, the effect is very similar, when passing an argument by reference, you don't explicitly give the address; so, in your code, the call should be as shown below. Also, as noted in the answer given by Vettri, your function does not return a double value (or, indeed, anything, as it is void), so you can't assign the variable yo directly from the call to it.

Try this, as one possible solution:

test(rdefined); // Changes the value of "rdefined"
double yo = rdefined; // Assigns modified value to "yo"

For a discussion on the differences between pointers and references, see here.

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
1

Corrected Solution:

#include <iostream>

using namespace std;

double test(double* r)
{
    *r = 0.1;
    return *r;
}

int main() {
    double rdefined;
    double yo = test(&rdefined);
    cout << yo <<endl;
    return 0;
}

You need to specify the correct return value. You got an error because you are expecting a double value in return of your test function, but you declared it as void.

Błażej Michalik
  • 4,474
  • 40
  • 55
Vettri
  • 7
  • 4
0

The only thing you need to do is, to replace & with * in the function parameters. here is the code.

#include <iostream>

using namespace std;

void test(double* r)
{
    *r = 0.1;
}

int main() {
    double rdefined;
    test(&rdefined);
    cout << rdefined <<endl;
    return 0;
}
Aqeel Ahmad
  • 709
  • 7
  • 20