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

后端 未结 10 1114
生来不讨喜
生来不讨喜 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:51

    In C, there are no any reference variables, but you can pass by reference with using pointers.

    In wikipedia, there is this definition. In call-by-reference evaluation (also referred to as pass-by-reference), a function receives an implicit reference to a variable used as argument, rather than a copy of its value. So this term is for type of parameter passing as mentioned by Thomas. So yes, since C is older than C++, also this idea is older than C++.

    However, in C++ both pointers and references can be used for passing to the function(Call by address and call by reference). Actually they are working the same way, they have only a few differences.

    • Once a reference is created, it cannot be later made to reference another object; it cannot be reseated. This is often done with pointers.
    • References cannot be NULL. Pointers are often made NULL to indicate that they are not pointing to any valid thing.
    • A reference must be initialized when declared. There is no such restriction with pointers

    With these differences, if you use call by reference instead of call by pointer, you can reduce the possibility of NULL pointer error kind of problems.

提交回复
热议问题