Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
How to compare pointers in C/C++?
The pointers can be directly compared using relational operators. In this article, we will learn about the comparisons of the pointers with the help of examples.
Pointers Comparison in C and C++
In C/C++, we can directly compare the pointers using relational operators (==, !=, <, >, <=, >=). These operators are used to compare two variables, values, or pointers. It returns a Boolean true value when the comparison is correct otherwise, it is false.
The core syntaxes of C and C++ pointers are similar such as declaration, dereferencing, and pointer arithmetic. All of these are identical in behavior and still use * and & in the same way.
Example of C Pointers Comparison
In this example, we declare two integer pointers say (*p1 and *p2), and then randomly allocate these pointer memory addresses of 200 and 300 respectively. Then, we check the conditions p1 > p2 using an if-statement where address 200 is greater than 300 which results in false and else part printed.
#include<stdio.h>
int main()
{
int *p2;
int *p1;
p2 = (int *)300;
p1 = (int *)200;
if(p1 > p2) {
printf("P1 is greater than p2");
} else {
printf("P2 is greater than p1");
}
return 0;
}
The above code produces the following result:
P2 is greater than p1
Example of C++ Pointers Comparison
In this example, we declare three pointers say (*ptr1, *ptr2, and *ptr3) where ptr2 has different memory allocation. While taking a comparison of each pointer with others it returns the result in the form of a boolean value.
#include<iostream>
using namespace std;
int main() {
int a = 10, b = 20;
int *ptr1 = &a;
int *ptr2 = &b;
int *ptr3 = &a;
cout << "ptr1 == ptr2: " << (ptr1 == ptr2 ? "true" : "false") << endl;
cout << "ptr1 == ptr3: " << (ptr1 == ptr3 ? "true" : "false") << endl;
cout << "ptr1 != ptr2: " << (ptr1 != ptr2 ? "true" : "false") << endl;
if (ptr1 < ptr2)
cout << "ptr1 points to a lower address than ptr2" << endl;
else
cout << "ptr1 does not point to a lower address than ptr2" << endl;
return 0;
}
The above code produces the following result:
ptr1 == ptr2: false ptr1 == ptr3: true ptr1 != ptr2: true ptr1 points to a lower address than ptr2
