Home >Backend Development >C++ >Are Pointer and Reference Parameters Functionally Identical in C ?

Are Pointer and Reference Parameters Functionally Identical in C ?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-03 02:13:29733browse

Are Pointer and Reference Parameters Functionally Identical in C  ?

Pointer vs. Reference Parameters: A Detailed Examination

Question:

Do pointer parameters (e.g., int foo(bar* p) { ... }) and reference parameters (e.g., int foo(bar& r) { ... }) behave identically in C ?

Answer:

The difference between pointers and references goes beyond their implementation details in the standard. References embody a syntactic sugar concept, essentially creating aliases for variables. This allows compilers to optimize code where pointers would otherwise add complexity.

Functional Equivalence:

Assuming no null pointer concerns, the functions foo(bar* p) and foo(bar& r) are essentially equivalent if the someInt() method is not virtual. Both functions directly access the object's member function through the parameter. If someInt() is virtual, however, the reference-based parameter function (foo(bar& r)) will invoke the correct method based on the actual object's type, while the pointer-based function (foo(bar* p)) will always invoke the base class method.

Assigning to a Reference:

The assignment bar& ref = *ptr_to_bar will not cause any slicing. The reference ref will alias the object pointed to by ptr_to_bar, allowing you to access its members directly.

Additional Differences:

  • References cannot be assigned NULL.
  • The address of a pointer yields the address of the pointer variable, while the address of a reference yields the address of the referenced variable.
  • References cannot be reassigned once initialized.

The above is the detailed content of Are Pointer and Reference Parameters Functionally Identical in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn