Meaning of pass by reference in C and C++?

后端 未结 10 1102
生来不讨喜
生来不讨喜 2020-12-17 20:46

I am confused about the meaning of \"pass by reference\" in C and C++.

In C, there are no references. So I guess pass by reference means passing a pointer. But then

10条回答
  •  一向
    一向 (楼主)
    2020-12-17 21:26

    A reference in general is an instance that is referencing something else. Thus in a wider sense, also a pointer can be considered as one possible implementation of a reference. References in C++ are just called references, because apart from referencing something they offer no other features.

    Pass-by-reference is used in general to distinguish from pass-by-value. Whether it is via pointer or via a reference is often just a minor detail. However, with C++ references it is imho more clear what is the purpose of the function parameter. Eg:

    int foo(int& a);         // pass-by-reference
    int foo(const int& a);   // is pratically pass-by-value 
                             // (+ avoiding the copy of the parameter)
    

    on the other hand, with references (as compared to pointers) it is not so obvious at the call site if it is pass-by-value or pass-by-reference. E.g.

    int x;
    int y = foo(x);  // could be pass-by-value or pass-by-reference
    int z = foo(&x); // obviously pass-by-reference (as a pointer)
    

提交回复
热议问题