Difference between ++*p, *p++ and *++p in c++

C++Server Side ProgrammingProgramming

In this section we will see what are the differences between *ptr++, *++ptr and ++*ptr in C++.

Here we will see the precedence of postfix++ and prefix++ in C or C++. The precedence of prefix ++ or -- has higher priority than dereference operator ‘*’ and postfix ++ or -- has priority higher than both prefix ++ and dereference operator ‘*’.

When ptr is a pointer, then *ptr++ indicates *(ptr++) and ++*prt refers ++(*ptr)

Example Code

 Live Demo

#include<iostream>
using namespace std;
int main() {
   char arr[] = "Hello World";
   char *ptr = arr;
   ++*ptr;
   cout << *ptr;
   return 0;
}

Output

I

So here at first ptr is pointing ‘H’. after using ++*ptr it increases H by 1, and now the value is ‘I’.

Example Code (C++)

#include<iostream>
using namespace std;
int main() {
   char arr[] = "Hello World";
   char *ptr = arr;
   *ptr++;
   cout << *ptr;
   return 0;
}

Output

e

So here at first ptr is pointing ‘H’. after using *ptr++ it increases the pointer, so ptr will point to the next element. so the result is ‘e’.

Example Code (C++)

 Live Demo

#include<iostream>
using namespace std;
int main() {
   char arr[] = "Hello World";
   char *ptr = arr;
   *++ptr;
   cout << *ptr;
   return 0;
}

Output

e

In this example also we are increasing the ptr using ++, where the precedence of pre-increment ++ is higher, then it increases the pointer first, then taking the value using *. so it is printing ‘e’.

raja
Published on 03-Apr-2019 09:31:54
Advertisements