Arrays passed by reference by default?

前端 未结 3 750
死守一世寂寞
死守一世寂寞 2020-12-14 01:51

I\'m reading a C++ book which says this:

C++ passes arrays to functions by reference—the called functions can modify the element values in the callers

3条回答
  •  一向
    一向 (楼主)
    2020-12-14 02:06

    To summarise my comment, you are absolutely right!

    The book is wrong in its choice of jargon. It tries to talk about arrays decaying to C pointers. It refers to passing this pointer by value as passing by reference which is WRONG.

    This is a common enough misconception, I believe I was taught this way as well (passing pointer as value == passing by reference). This is completely wrong in terms of C++ references and pass by reference.

    If this were correct, I wouldn't be able to do this..

    void ModifyMyArray(int *array){
       int oops[4]= {0};
       array = oops;
    
       array[2] = 1;
    }
    ...
    int MyArray[4] = {1,3,5,7};
    
    ModifyMyArray(MyArray);
    

    Similar to this question in Java - Is Java "pass-by-reference" or "pass-by-value"?

提交回复
热议问题