Return by value
Return by value is the simplest and safest return type to use. When a value is returned by value, a copy of that value is returned to the caller. Eg:
int returnC() {
return c;
}
Return by reference
Just like with pass by reference, values returned by reference must be variables (you can not return a reference to a literal or an expression). When a variable is returned by reference, a reference to the variable is passed back to the caller. The caller can then use this reference to continue modifying the variable, which can be useful at times. Return by reference is also fast, which can be useful when returning structs and classes. Eg:
// This struct holds an array of 25 integers
struct MyArrays
{
int ArrValue[25];
};
// Returns a reference to the nIndex element of rArray
int& Value(MyArrays &rArray, int nIndex)
{
return rArray.ArrValue[nIndex];
}
int main()
{
MyArrays objArray;
// Set the 10th element of objArray to the value 5
Value(objArray, 10) = 5;
cout << objArray.ArrValue[10] << endl;
return 0;
}