Aug 11, 2014

C Programming #44: Pointer - other operators

This article will cover what operators other than arithmetic operator can be used with pointers. It is extension of previous article C Programming #42: Pointer - arithmetic.

Relational Operators and Pointer

Comparing the pointers are allowed. Following program demonstrates it.

#include <stdio.h>
int main()
{
   int i, j ,k;
   int *pi = &i, *pj = &j, *pk = &k;
                                                                                
   printf("Pointer pi is %p\n", pi);
   printf("Pointer pj is %p\n", pj);
   printf("Pointer pk is %p\n", pk);

   printf("Pointer comparison\n");
   printf("pj > pi is  %d\n", pj > pi);
   printf("pk < pi is  %d\n", pk < pi);
   printf("pk == pk is %d\n", pk == pk);
   printf("pk == NULL is %d\n", pk == NULL);

   return 0;
}
Output of above program is

Pointer pi is 0x7fffcd109b84
Pointer pj is 0x7fffcd109b88
Pointer pk is 0x7fffcd109b8c
Pointer comparison
pj > pi is  1
pk < pi is  0
pk == pk is 1
pk == NULL is 0
Hence Following Comparison operators are allowed with Pointer variables.
  1. Greater than  >
  2. Less than <
  3. Greater than or equal to >=
  4. Less than or equal to  <=
  5. Equal to  ==
  6. Not equal to  !=
Generally Pointers of same type are compared.  While you could compare pointers of different type using typecasting. Which will be covered later.


Logical  Operators and Pointer

Logical operator works with pointers. Following program will demonstrate it:-


#include <stdio.h>
int main()
{
   int i, j ,k;
   int *pi = &i, *pj = &j, *pk = &k;

   printf("Pointer pi is %p\n", pi);
   printf("Pointer pj is %p\n", pj);
   printf("Pointer pk is %p\n", pk);

   printf("Pointer logical operator\n");
   printf("pk || pi is  %d\n", pk || pi);
   printf("pj && NULL is  %d\n", pj && NULL);                                   
   printf("!pk is %d\n", !pk);

   return 0;
}
Output of above program is

Pointer pi is 0x7fff38ebf494
Pointer pj is 0x7fff38ebf498
Pointer pk is 0x7fff38ebf49c
Pointer logical operator
pk || pi is  1
pj && NULL is  0
!pk is 0

Bitwise Operators and Pointer 

Pointers variables are not allowed with bitwise operators.

Links

Next Article - C Programming #45: Pointer - as function parameter and return value
Previous Article - C Programming #43: Pointer - NULL

All Article - C Programming

No comments :

Post a Comment