Why?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • randysimes
    New Member
    • Oct 2009
    • 54

    Why?

    I was wondering why the output of the following code is:
    x = 1
    y = 2
    z = 3
    x = 2 (understand here up)
    y = 2 (Why isn't it 3)
    z = 5 (Why isn't it 4)
    Code:
    int F(int& x, int y)
    {
    x = x+1;
    y = y +1;
    return x + y;
    }
    
    int main()
    {
    int x, y, z;
    x = 1, y = 2, z = 3;
    std::cout << "x=" << x << '\n'
                  << "y=" << y << '\n'
                  << "z=" << z << '\n';
    z = F(x,y);
    std::cout << "x=" << x << '\n'
                  << "y=" << y << '\n'
                  << "z=" << z << '\n';
    return 0;
    }
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    It has do do with the differing types of the parameters to F

    int F(int& x, int y);

    If you know and understand the difference between the declarations of the parameters int& x and int y then you should be able to easily explain your results.

    So do you know what that & in the declaration means and what that in turn implies for program execution?

    Comment

    • randysimes
      New Member
      • Oct 2009
      • 54

      #3
      I can see that you can change the value of the & variable, that it.

      Comment

      • Banfa
        Recognized Expert Expert
        • Feb 2006
        • 9067

        #4
        That is the effect but the question you need to answer is what is the syntactic meaning of the & in this construct? Why does it cause the value of x outside the function to be modified.

        Comment

        • randysimes
          New Member
          • Oct 2009
          • 54

          #5
          Is it the addess of the variable or is it passed by reference? I couldn't find much about & online.

          Comment

          • Frinavale
            Recognized Expert Expert
            • Oct 2006
            • 9749

            #6
            You'd be interested in looking up the topic of pointers and passing parameters by reference.

            Comment

            • Banfa
              Recognized Expert Expert
              • Feb 2006
              • 9067

              #7
              Try reading this

              Comment

              Working...