Difference between ++*p, *p++ and *++p

Difference between ++*p, *p++ and *++p

To understand the difference between ++*p, *p++, and *++p. We need to understand the precedence and associativity of the operators. We will also see some C programs related to these operators.

Evaluating postfix, prefix, and *:

  • Precedence of postfix ++ is higher than prefix ++ and their associativity is also different.
  • Associativity of postfix ++ is left to right.
  • Associativity of prefix ++ is right to left.
  • The precedence of prefix ++ and * is the same with the right to left associativity.
  • Precedence of postfix ++ is higher than * and their associativity is also different.

 

Now I think you are familiar with the precedence and associativity of the postfix, prefix, and * operators. So let us see some programs to understand the difference between ++*p, *p++, and *++p.

 

C program using expression ++*p :

 

#include <stdio.h>

int main()
{
    int arr[5] = {100,200,300,400,500};

    int *p = arr;

    ++*p;

    printf("arr[0] = %d, arr[1] = %d, *p = %d", arr[0], arr[1], *p);

    return 0;
}

Output: 101 , 200 , 101

Explanation:

In the above example, two operators are involved and both have the same precedence with a right to left associativity. So compiler looks for associativity and the above expression ++*p is equivalent to ++ (*p). In another word, we can say it is pre-increment of value, and output is 101, 200, 101.

 

C program using expression *p++ :

 

#include <stdio.h>

int main()
{
    int arr[5] = {100,200,300,400,500};

    int *p = arr;

    *p++;

    printf("arr[0] = %d, arr[1] = %d, *p = %d", arr[0], arr[1], *p);

    return 0;
}

Output: 100, 200, 200

Explanation:

In the above example, two operators are involved and both have different precedence. The precedence of post ++ is higher than the *, so first post ++ will be executed and above expression, *p++ will be equivalent to *(p++). In another word you can say that it is post-increment of address and output is 100, 200, 200.

 

 

C program using expression *++p :

 

#include <stdio.h>

int main()
{
    int arr[5] = {100,200,300,400,500};

    int *p = arr;

    *++p;

    printf("arr[0] = %d, arr[1] = %d, *p = %d", arr[0], arr[1], *p);

    return 0;
}

Output: 100, 200, 200

Explanation:

In the above example, two operators are involved and both have the same precedence with the right to left associativity. So compiler looks for associativity and the above expression *++p is equivalent to *(++p). In another word you can say it is pre-increment of address and output is 100, 200,200.

Recommended Articles for you: