0

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;
}
StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
  • The first line of code contained #include . – Lin Rung-Bin Dec 05 '17 at 10:45
  • 1
    The order of evaluation in `std::cout` is unspecified. It is not left-to-right, right-to-left, or anything else. That might be your problem. Anyway you define the function prototypes in main, that is weird!? – xander Dec 05 '17 at 10:46
  • 1
    The first occurrence of the printing of cube is neatly hidden on the right of the code so it would not be too obvious what the actual issue is. – stefaanv Dec 05 '17 at 10:52
  • Got it. Thank a lot for the helps. – Lin Rung-Bin Dec 07 '17 at 07:27

0 Answers0