Arrays passed by reference by default?

前端 未结 3 753
死守一世寂寞
死守一世寂寞 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:05

    It is true that when you pass an array to a function that you are actually passing a pointer by value. However, I feel that for people just learning C++ they should not have to worry about pointers at all. They learn that you can pass a variable by value or by reference to a function.

    By value means that changes to the variable in the function don't affect the original value in the calling function.

    By reference means that if the function changes the value of the variable then those changes will be seen in the original calling function.

    When an array is a parameter of a function (without the const keyword) then any changes made to the values in the array will be seen in the original calling function. Therefore, we say that arrays are passed by reference by default. This avoids having to explain what pointers are which really isn't that relevant in passing statically declared arrays around, yet it lets people know that if they mess with the values in the array in the called function that those changes will persist in the calling function.

    I teach a "first-course" Computer Science C++ course at a top-notch engineering school (our programming team is going to the World Finals in Russia this year). About 90% of the people in the class aren't actually computer related majors (mostly mechanical engineers). The above material is more than enough to confuse them without having to explain what pointers are. That is why that book and others mention that arrays are passed by reference because many people reading the books just need "just enough" C++ to get them by without having to learn every little detail. Those that really want to program should have no problem transitioning to fact that arrays are really passed by pointer.

    Just my opinion though.

提交回复
热议问题