What happens to a parameter passed by value that is modified locally?

后端 未结 5 388
粉色の甜心
粉色の甜心 2021-01-24 19:53

I am well aware that modifying a function\'s argument that is passed by value is ineffective outside of the C/C++ function, but compilers allow it - but what happens? Is a loca

5条回答
  •  终归单人心
    2021-01-24 20:22

    As others have explained, x is local in function doSomething, any modifications only affect the local copy of the argument.

    Note however that C++ allows passing by reference: a very small change in the definition of doSomething() would have significant consequences for this program:

    void doSomething( int& x ) {
        x = 42;
        printf( "The answer to Life, the Universe and Everything is (always): %i!\n", x );
    }
    

    With the above function definition, variable a in main would indeed have its value changed to 42. Since the code in main() is identical, this C++ feature can lead to confusing code, especially for a C programmer.

提交回复
热议问题