Output of the Expressions : ++*p, *p++,*++p

One of the most complicated pointer question asked in interviews

Q. What will be the output of the pointer expressions: ++*p, *p++,*++p. And what is the difference between the three.
These kind of questions are easy to solve. But the condition is that you should know the associativity and precedence rules for the three operators namely : Postfix:”++” operator, Prefix:”++” operator and Dereference”*” operator.

Today I am going to explain these concepts with example

Precedence and Associativity of postfix ++, Prefix ++, *(dereference) operator

The value of such expressions (*++p, ++*p etc.) can be easily calculated by remembering following simple rules about postfix operator ++, prefix operator ++ and * (dereference) operators
1) Precedence of postfix operator ++ is higher than both * and prefix operator ++. 
Associativity of postfix operator ++ is left to right.
2)  Precedence of prefix operator ++ and *(dereference) operator is same.
Associativity of both is right to left.

Let Us Understand each of the above expressions one by one with Examples:

1 . ++*p

look at the following code:

#include <stdio.h>
int main(void)
{
    int array[] = {20, 50, 100};
    int *p = array;
    ++*p;
    printf(“*p = %d”,*p);
    return 0;
}

Explanation:
The expression ++*p has two operators of same precedence (++,*). So compiler looks for associativity. Associativity of operators is right to left. Therefore the expression is treated as ++(*p).

Therefore the output of above program is “*p = 21“.

2. *p++


look at the following code:

#include <stdio.h>
int main(void)
{
    int array[] = {20,50,100};
    int *p = array;
*p++;
    printf(“*p = %d”, *p);
return 0;
}

Explanation:
The expression *p++ is treated as *(p++)
because the precedence of postfix operator ++ is higher than *.
Therefore the output of the above program is “*p = 50“.

3. *++p


look at the following code:

#include <stdio.h>
int main(void)
{
    int array[] = {20,50,100};               
   int *p = array;
*++p;
    printf(“*p = %d”,*p);
return 0;
}

The expression *++p has two operators of same precedence, so compiler looks for associativity. Associativity of operators is right to left. Therefore the expression is treated as *(++p).
Therefore the output of the above program is “*p = 50“.

I hope this will clear the things up.

Share
loading...

Leave a Reply

Your email address will not be published. Required fields are marked *