passing by reference

I'm trying to pass by reference. I know you have to add an ampersand to the function prototype, but im not quite sure what i am supposed to put in the function description.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
 #include <iostream>
using namespace std; 

 double celsius_to_fahrenheit(double);


int main()
 {
  
  double fahrenheit;
  double celsius = 22.5;


  fahrenheit = celsius_to_fahrenheit(celsius);

  cout << celsius << " C = " << fahrenheit << " F\n";
  system ("pause");
  return 0;
 } 

double celsius_to_fahrenheit (double &celsius)
 {
  return(celsius * (9.0/5.0) + 32.0);
 
 }
Umm..Firstly you need amperstand in your prototype secondly that's not how you use references you would return void and set a new value for celsius and it will directly modify the varaible being passed as a param.

1
2
celsius *= (9.0/5.0);
celsius += 32;
A temperature conversion function is not a good candidate for pass-by-reference - you should try with something else instead.
The function definition has to match the declaration. You can leave out the variable name(s) in the definition but they are usually included for clarity.
So double celsius_to_fahrenheit(double &); will compile
but double celsius_to_fahrenheit(double &celsius); is preferred.
Passing by reference is best used in two situations (of which neither apply here):
1) The object passed is a complex class which will be expensive to copy
2) You want to modify the original object in your function

Also, when I declare references i like to do this double& celsius instead of double &celsius. This is a personal preference but I like it because in this case, & is not getting the address, but is part of the type. You are saying "I want a reference to a double". Similarly, for pointers I like: double* celsius over double *celsius. I only attach the * to the object when I am dereferencing.

So to answer your question directly, you would do this:

1
2
3
4
5
6
7
8
9
10
11
12
void setToZero(double& value);

int main()
{
    double something;
    setToZero(something); // something gets set to 0.0;
}

void setToZero(double& value)
{
    value = 0.0;
}
Last edited on
thank you for the feedback. The reason i am using this program is because the book i bought to self teach myself gave me this as a project.
What is the book called?
Topic archived. No new replies allowed.