When pass a variable to a function, why the function only gets a duplicate of the variable?

前端 未结 9 1308
野的像风
野的像风 2020-12-06 18:05

When pass a variable to a function, why the function only gets a copy/duplicate of the variable?

int n=1;

void foo(int i)
{
    i++;
}

As

9条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-06 18:36

    In order to change the value of a parameter you need to pass by reference using the '&' symbol.

    The reason this is done is so that you can choose whether or not you want changes to stick with your variable. If you pass by value you can be sure that it will not change and cause an error in your program.

提交回复
热议问题