- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Difference between ++*p, *p++ and *++p in c++
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
#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++)
#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’.