-
September 25th, 2012, 07:19 PM
#1
passing a function parameter by reference
Hello, I created the following code to pass the the variable 'inputVoltage' by reference to the function 'input'. It certainly works when I run the program, but I dont think it is a standard way of doing it, i.e. the use of '*' and '&' is not according to convention ?
Or perhaps the way did it is acceptable ?
Thanks for any confirmation either way.
int input (double *inputVoltage);
int main ( {
double inputVoltage;
input(&inputVoltage);
return 0;
}
int input(double* inputVoltage)
{
cin >> *inputVoltage;
etc.
etc.
}
-
September 25th, 2012, 08:02 PM
#2
Re: passing a function parameter by reference
Originally Posted by fran1942
Hello, I created the following code to pass the the variable 'inputVoltage' by reference to the function 'input'. It certainly works when I run the program, but I dont think it is a standard way of doing it, i.e. the use of '*' and '&' is not according to convention ?
You're being confused with reference and the address-of operator. These entities use the same symbol ('&') but have vastly different meanings.
In your example, you are not using references anywhere. You are passing the address-of inputVoltage to the function, not a reference.
Code:
int input (double *inputVoltage); // expects a pointer to double
int input (double& inputVoltage); // expects a reference to double
int main
{
double inputVoltage;
input(&inputVoltage); // calls the pointer version
input(inputVoltage); // calls the reference version
}
Regards,
Paul McKenzie
-
September 26th, 2012, 04:35 AM
#3
Re: passing a function parameter by reference
Originally Posted by fran1942
Hello, I created the following code to pass the the variable 'inputVoltage' by reference to the function 'input'. It certainly works when I run the program, but I dont think it is a standard way of doing it, i.e. the use of '*' and '&' is not according to convention ?
Or perhaps the way did it is acceptable ?
Your approach would be conventional if you were programming in C, because references don't exist is C.
However, in C++ you do have the choice to use either a pointer or a reference for you function argument. Using a pointer only makes sense if a NULL pointer has a special meaning. In your case it doesn't, in fact it would cause a problem, so you should use a reference instead of a pointer to clearly communicate that your function really needs to have a valid variable to write to.
Cheers, D Drmmr
Please put [code][/code] tags around your code to preserve indentation and make it more readable.
As long as man ascribes to himself what is merely a posibility, he will not work for the attainment of it. - P. D. Ouspensky
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|