How to compare pointers in C/C++?


We can compare pointers if they are pointing to the same array. Relational pointers can be used to compare two pointers. Pointers can’t be multiplied or divided.

In C

Example

 Live Demo

#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);
}

Output

P2 is greater than p1

In C++

Example

#include <iostream>
using namespace std;
int main() {
   int *p2;
   int *p1;
   p2 = (int *)300;
   p1 = (int *)200;
   if(p1>p2) {
      cout<<"P1 is greater than p2";
   } else {
      cout<<"P2 is greater than p1";
   }
   return(0);
}

Output

P2 is greater than p1

Some Key points about pointer comparison −

  • p1<=p2 and p1>=p2 both yield true and p1<p2 and p1>p2 both yield false, if two pointers p1 and p2 of the same type point to the same object or function, or both point one past the end of the same array, or are both null.

  • p1<p2, p1>p2, p1<=p2 and p1>=p2 are unspecified, if two pointers p1 and p2 of the same type point to different objects that are not members of the same object or elements of the same array or to different functions, or if only one of them is null.

  • If two pointers point to non-static data members of the same object, or to subobjects or array elements of such members, with same access control then the result is specified.

  • the result is unspecified, if two pointers point to non-static data members of the same object with different access control.

Updated on: 30-Jul-2019

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements