Home  >  Article  >  Backend Development  >  Pointers vs. References in C Functions: Functional Equivalence or Subtle Differences?

Pointers vs. References in C Functions: Functional Equivalence or Subtle Differences?

Susan Sarandon
Susan SarandonOriginal
2024-11-03 00:43:291002browse

Pointers vs. References in C   Functions: Functional Equivalence or Subtle Differences?

Pointer vs. Reference Parameters: Functional Equivalence and Subtle Differences

In C , pointers and references are both used as parameters to functions, but they differ in their behavior and semantics. Let's delve into the key differences between these two parameter types.

Are foo() and foo() Equivalent?

The snippet below demonstrates two functions with different parameter types:

<code class="cpp">int foo(bar* p) {
  return p->someInt();
}

int foo(bar& r) {
  return r.someInt();
}</code>

Functionally, these two functions are equivalent if the following conditions are met:

  • someInt() is not virtual.
  • The functions are passed an instance of bar or its subclasses.

The reason is that both pointer and reference parameters provide direct access to the same memory location. In this case, the difference in access syntax (., ->) is insignificant.

Assignment via Pointer and Reference

The line below demonstrates an assignment operation involving a pointer and a reference:

<code class="cpp">bar& ref = *ptr_to_bar;</code>

This assignment does not involve any slicing or loss of data. It assigns the value of the object pointed to by ptr_to_bar to the reference ref.

Subtle Differences Beyond Functionality

While pointers and references have equivalent functionality in the example above, there are subtle differences to note:

  • Nullable: Pointers can be assigned NULL, while references cannot.
  • Dereferencing: Taking the address of a pointer yields the address of the pointer variable, while taking the address of a reference yields the address of the referenced variable.
  • Reassignment: References cannot be reassigned once initialized, while pointers can be reassigned to point to different objects.

The above is the detailed content of Pointers vs. References in C Functions: Functional Equivalence or Subtle Differences?. 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