Precedence of postfix ++ and prefix ++ in C/C++

CC++Server Side ProgrammingProgramming

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

 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

 Live Demo

#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’.

raja
Published on 03-Apr-2019 06:55:24
Advertisements