The main function calls squareByValue(int, int &) to compute the square and the cube of x. The square of x is returned by the function using return statement. The cube is returned to main function using a pass-by-reference variable called cube. However, I found that cube does not have a correct value being printed out by the insertion operator chain. Nevertheless, it's value is correctly printed out in the next cout statement. I can not understand why this happens, i.e., why the first print-out of cube is not correct. Thanks.
#include <iostream>
using namespace std;
int main()
{
int x = 2;
int squareByValue(int, int &);
void squareByReference(int &);
int cube;
cout << " x= " << x << " before squared by calling squareByValue " << endl;
cout << " The square of x = " << squareByValue(x, cube) << " after calling squareByValue." << " Cube= " << cube << endl;
cout << "Cube= " << cube << endl;
cout << " x= " << x << " after calling squareByValue" << endl;
}
int squareByValue (int number, int& cube){
cube = number*number*number;
return number*number;
}