confused on passing by reference

what im really trying to do is to have this program calculate the equation i have but instead of it printing out 10 its suppose to print out 20. essentially i want it to update x every time its been used. i figured passing by reference is the way to do this but i keep getting 10. i want to solve this by without having to break the equation apart in several pieces if possible. thank you for your help and advice in advance.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  #include <iostream>

using namespace std;

void calculate(int&);

int main()
{

 int x=2;
 calculate(x);
 cout<<x<<endl;

    return 0;
}

void calculate(int& x)
{
 int x = x*x+2*x+x;
}
check line 19 formula
Line 19 creates a whole new variable named x.

Perhaps you meant:
x = x*x+2*x+x;

That said, if x begins life as 2, then
x = x*x+2*x+x;
means
x = 2*2 + 2*2 + 2
= 4 + 4 + 2
= 10

Seems pretty reasonable to me.
Last edited on
Topic archived. No new replies allowed.