-3
void func(int x) {
 x = 2;
}

int main()
{
 int x = 3;
 func(x);
 cout << "x = " << x << endl;
 return 0;
}

I expect the out put to be 2. Why isn't this happening? A simple explanation since I only just started learning c++ please. Could you then explain why the following yields 5:

void func(int x)
{
 x = 2;
}


void function(int *x)
{
 *x = 5;
}

int main()
{
 int x = 3;
 func(x);
 function(&x);
 cout << "x = "<< x << endl;
 return 0;
}
mtheorylord
  • 115
  • 9
  • 1
    Possible duplicate of [When I change a parameter inside a function, does it change for the caller, too?](http://stackoverflow.com/questions/1698660/when-i-change-a-parameter-inside-a-function-does-it-change-for-the-caller-too) – Jason C Dec 11 '16 at 01:21
  • See also http://stackoverflow.com/questions/11736306/when-pass-a-variable-to-a-function-why-the-function-only-gets-a-duplicate-of-th, http://stackoverflow.com/questions/21215409/does-c-pass-objects-by-value-or-reference, and a basic tutorial on C++ functions: http://www.cplusplus.com/doc/tutorial/functions/, and for your pointer example: http://cslibrary.stanford.edu/104/ (the C++ version). – Jason C Dec 11 '16 at 01:22

1 Answers1

1

I expect the out put to be 2. Why isn't this happening?

Because you are passing by value, the parameter is just a copy of the original argument - so whatever you change x in func does not affect the original x in main.

As you need to change the argument inside the function, C++ passing by reference is precisely what you need:

void func(int &x)
{
    x = 2;
}

As with your edit:

void function(int *x)

That is pass-by-pointer - if you pass a pointer to x, you can change x indirectly in main. This is normally used in C, but as you are using C++ pass-by-reference as the above is the preferred method.

artm
  • 17,291
  • 6
  • 38
  • 54