Is C++ Array passed by reference or by pointer?

前端 未结 3 605
臣服心动
臣服心动 2021-01-05 17:09

In school, our lecturer taught us that the entire array was passed by reference when we pass it to a function,.

However, recently I read a book. It

3条回答
  •  北海茫月
    2021-01-05 17:46

    At worst, your lecturer is wrong. At best, he was simplifying terminology, and confusing you in the process. This is reasonably commonplace in software education, unfortunately. The truth is, many books get this wrong as well; the array is not "passed" at all, either "by pointer" or "by reference".

    In fact, because arrays cannot be passed by value due to an old C restriction, there is some special magic that happens with arrays as function arguments.

    The function declaration:

    void funcA(int[]);
    

    is silently translated into the following:

    void funcA(int*);
    

    and when you write this:

    funcA(myArray);
    

    it is silently translated into the following:

    funcA(&myArray[0]);
    

    The result is that you're not passing the array at all; you pass a pointer to its first element.

    Now, at certain levels of abstraction/simplification, you can call this "passing an array by pointer", "passing an array by reference" or even "passing a handle to an array", but if you want to talk in C++ terms, none of those phrases are accurate.

提交回复
热议问题