pointers and reference variables
i am mixing up my reference and pointer variables. need a bit of guidance. i am trying to return a value by reference from a function.
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 26 27 28 29 30 31 32 33 34 35 36
|
//
#include "stdafx.h"
#include <iostream>
#include <iomanip>
using namespace std;
// FUNCTION PROTOTYPE
double convert(double *measurement);
int main()
{
double measurement;
cout << "Enter a length in inches and I will convert it to centimeters:\n";
cin >> measurement;
convert(&measurement);
cout << setprecision(4);
cout << fixed << showpoint;
cout << "Value in centimeters: " << measurement << endl;
system("pause");
return 0;
}
/***********
convert
***********/
double convert(double *measurement)
{
return *measurement * 2.54;
}
|
If you want to return by reference, you need to change your function header to show that.
int& foo(int* ptr);
There's an example that takes a pointer to an int as a parameter, and returns a reference to an int as a return value.
In convert you are passing in a pointer and returning a value. If you want to work with a reference then perhaps:
1 2 3 4
|
void convert(double &measurement)
{
measurement *= 2.54;
}
|
then you would just pass by convert(measurement) instead of passing a pointer
Last edited on
ok. those are both helpful. thank you ResidentBiscuit and Texan40. let me see what I can do.
ok. i got it i think. this one compiles and runs.
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 26 27 28 29 30 31 32 33 34 35 36
|
//
#include "stdafx.h"
#include <iostream>
#include <iomanip>
using namespace std;
// FUNCTION PROTOTYPE
void convert(double *);
int main()
{
double measurement;
cout << "Enter a length in inches and I will convert it to centimeters:\n";
cin >> measurement;
convert(&measurement);
cout << setprecision(4);
cout << fixed << showpoint;
cout << "Value in centimeters: " << measurement << endl;
system("pause");
return 0;
}
/***********
convert
***********/
void convert(double *measurement)
{
*measurement *= 2.54;
}
|
Topic archived. No new replies allowed.