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

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

    Most modern languages are defined to use pass by value. The reason is simple: it significantly simplifies reasoning about the code if you know that a function cannot change your local state. You can always pass by non-const reference if you want a function to be able to modify local state, but such cases should be extremely rare.

    EDITED to respond to updated question:

    No, you're not right. Pass by value is the simplest mechanism for passing parameters. Pass by reference or copy-in/copy-out are more complex (and of course, Algol's expression replacement is the most complicated).

    Think about it for awhile. Consider f(10). With call by value, the compiler just pushes 10 on the stack, and the function just accesses the value in situ. With call by reference, the compiler must create a temporary, initialize it with 10, and then pass a pointer to it to the function. Inside the function, the compiler must generate an indirection each time it accesses the value.

    Also, protecting from modification inside the function doesn't really help readability. If the function takes no reference parameters, you know without looking inside the function that it cannot modify any variables you pass as arguments. Regardless of how anyone modifies the function in the future. (One could even argue that functions should not be allowed to modify global state. Which would make the implementation of rand() rather difficult. But would certainly help the optimizer.)

提交回复
热议问题