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

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

    One reason C is pass-by-value is that in FORTRAN, which is pass-by-reference, it was possible that you could call a subroutine with a call like “CALL MYROUTINE(3)”, and the subroutine would change the value of its argument. Then, after that point in the program, “3” would have the value given to it by the subroutine.

    Naturally, when this occurred, it caused great confusion. It made bugs hard to find, because source code did something very different from what it appeared to do.

    So, as people have learned about programming languages, one of the principles used in designing languages is to avoid things that made code hard to understand or that made bugs more likely. (This principle is not always successfully applied, as we are also tempted to give programming languages more expressive power and to enable compilers to optimize code.)

提交回复
热议问题