Home > Article > Backend Development > Rules and exceptions for pointer comparisons?
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 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:
Exception:
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!