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


Pointer Airthmetics

In C programming language, *p represents the value stored in a pointer. ++ is increment operator used in prefix and postfix expressions. * is dereference operator. Precedence of prefix ++ and * is same and both are right to left associative. Precedence of postfix ++ is higher than both prefix ++ and * and is left to right associative. See the below example to understand the difference between ++*p, *p++ and *++p.

Example (C)

 Live Demo

#include <stdio.h>
int main() {
   int arr[] = {20, 30, 40};
   int *p = arr;
   int q;
   //value of p (20) incremented by 1
   //and returned
   q = ++*p;
   printf("arr[0] = %d, arr[1] = %d, *p = %d, q = %d 
",    arr[0], arr[1], *p, q);    //value of p (20) is returned    //pointer incremented by 1    q = *p++;    printf("arr[0] = %d, arr[1] = %d, *p = %d, q = %d
",    arr[0], arr[1], *p, q);    //pointer incremented by 1    //value returned    q = *++p;    printf("arr[0] = %d, arr[1] = %d, *p = %d, q = %d
",    arr[0], arr[1], *p, q);    return 0; }

Output

arr[0] = 21, arr[1] = 30, *p = 21, q = 21
arr[0] = 21, arr[1] = 30, *p = 30, q = 21
arr[0] = 21, arr[1] = 30, *p = 40, q = 40

Updated on: 06-Jan-2020

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements