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

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

    It is to make sure that the function doesn't change the original value.

    0 讨论(0)
  • 2020-12-06 18:35

    Because C pass arguments by value.

    From Kernighan & Richtie 2nd edition : (1.8 Call by value) "In C all function arguments are passed by "value""

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题