问题描述:

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;

}

网友答案:

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.

相关阅读:
Top