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

前端 未结 9 1312
野的像风
野的像风 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:30

    I guess one reason is efficiency, it's more efficient to access values directly then through a pointer. Another advantage is choice, the C/C++ way you can choose to pass arguments by value or by pointer, your way you only have the choice to pass by pointer. But most importantly passing by value means that your function is isolated from the rest of your code, and changes to variables inside the function don't affect the rest of the code. Believe me you would get far more bugs and coding would be more difficult if this were not the case.

提交回复
热议问题