I'm working with using functions to return more than 1 value (using pointers/references) at the moment. I'm a little confused about the difference (if there even is one) and curious if it really matters. I want to know if one is more effective than the other, if one is necessary for some situations and the other is necessary for other situations, if it's all preference, etc. Here are my two codes (if anyone cares.)
// Passing pointers to a function
#include <iostream>
usingnamespace std;
int Factor(int n, int *Squared, int *Cubed);
int main()
{
int myNum;
int mySquared;
int myCubed;
cout << "Enter a number (0-20): ";
cin >> myNum;
int isGood = Factor(myNum, &mySquared, &myCubed);
if (isGood)
{
cout << "Squared: " << mySquared << endl;
cout << "Cubed: " << myCubed << endl;
} else {
cout << "ERROR!" << endl;
}
return 0;
}
int Factor(int n, int *Squared, int *Cubed)
{
int Value = 0;
if (n > 20 || n < 0)
{
Value = 0;
} else {
*Squared = n * n;
*Cubed = n * n * n;
Value = 1;
}
return Value;
}
// Passing references to a function
#include <iostream>
usingnamespace std;
int Factor(int n, int &Squared, int &Cubed);
int main()
{
int myNum;
int mySquared;
int myCubed;
cout << "Enter a number (0-20): ";
cin >> myNum;
int isGood = Factor(myNum, mySquared, myCubed);
if (isGood)
{
cout << "Squared: " << mySquared << endl;
cout << "Cubed: " << myCubed << endl;
} else {
cout << "ERROR!" << endl;
}
return 0;
}
int Factor(int n, int &Squared, int &Cubed)
{
int Value = 0;
if (n > 20 || n < 0)
{
Value = 0;
} else {
Squared = n * n;
Cubed = n * n * n;
Value = 1;
}
return Value;
}
References can be thought of as automatically dereferenced pointers that are always pointing to valid memory. If you use pointers, like in your first example, you need to check them for NULL. Unless someone is misusing a reference, they will never be NULL.
Also, references can be used without the asterisk. The only time I use pointers is when I am using someone else's library and their functions only take pointers. Use references whenever possible.
Buffbill I didn't technically mean a function returning more than one value. What I am talking about is using a function to change more than 1 value in a different scope than the functions. For example..
1 2
int i, j;
MyFunc(i, j);
Using a code such as the one above to change the value of both i and j without having to define a global variable.