Home >Backend Development >C++ >Rules and exceptions for pointer comparisons?

Rules and exceptions for pointer comparisons?

WBOY
WBOYOriginal
2024-06-04 18:01:16701browse

In C/C++, the pointer comparison rules are as follows: pointers pointing to the same object are equal. Pointers to different objects are not equal. Exception: Pointers to null addresses are equal.

Rules and exceptions for pointer comparisons?

Rules and Exceptions for Pointer Comparison

In C/C++ programming, a pointer is a type that can store the address of other variables. Special variables. Understanding the rules of pointer comparison is crucial to mastering the use of pointers.

Rule:

  • Two pointers pointing to the same object compare true (equal).
  • Comparison of two pointers pointing to different objects is false (not equal).

Exception:

  • The comparison is true when both pointers point to empty or null addresses.

Practical case:

The following C program demonstrates the rules and exceptions of pointer comparison:

#include <stdio.h>

int main() {
  int a = 10;
  int b = 20;
  int *ptr1 = &a;  // ptr1 指向 a
  int *ptr2 = &b;  // ptr2 指向 b
  int *nullPtr = NULL;  // 空指针

  // ptr1 和 ptr2 指向不同的对象
  if (ptr1 == ptr2) {
    printf("ptr1 和 ptr2 指向同一对象。\n");
  } else {
    printf("ptr1 和 ptr2 指向不同的对象。\n");
  }

  // ptr1 和 nullPtr 指向不同的对象
  if (ptr1 == nullPtr) {
    printf("ptr1 和 nullPtr 指向同一对象。\n");
  } else {
    printf("ptr1 和 nullPtr 指向不同的对象。\n");
  }

  // nullPtr 和 nullPtr 指向相同的空对象
  if (nullPtr == nullPtr) {
    printf("nullPtr 和 nullPtr 指向同一对象。\n");
  } else {
    printf("nullPtr 和 nullPtr 指向不同的对象。\n");
  }

  return 0;
}

Output:

ptr1 和 ptr2 指向不同的对象。
ptr1 和 nullPtr 指向不同的对象。
nullPtr 和 nullPtr 指向同一对象。

The above is the detailed content of Rules and exceptions for pointer comparisons?. 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