2,866 views
2 votes
2 votes

Consider the program:-

void main()

{

 int a[] = {0, 1, 2, 3, 4};

 int *p[] = { a, a+1, a+2, a+3, a+4 };

 int **ptr = p;

 ptr++;

 print( ptr - p, *ptr - p, **ptr );

 *ptr++;

 print( ptr - p, *ptr - a, **ptr );

 *++ptr;

 print( ptr - p, *ptr - a, **ptr );

 print(++*ptr);

}

Now my doubt is how these bold letter lines are working i.e. how pre increment and post increment are working on pointers?

1 Answer

Best answer
2 votes
2 votes

The operator precedence is as follows-

Operator

Description

Associativity


++ --

Postfix increment/decrement (see Note 2)

left-to-right

++ --
*
 
Prefix increment/decrement
Dereference
right-to-left

According to precedence table - 

We can see that ++(postfix) has higher precedence than * hence ,evaluate ++ (postfix) first then * hence *ptr++ = *(ptr++)

We can see that ++(prefix) has same precedence as *  but the expression will be evaluated from right to left , hence evaluate ++ (prefix) first then * hence *++ptr  = *(++ptr)

We can see that ++(prefix) has same precedence as *  but the expression will be evaluated from right to left , hence evaluate * first then ++(prefix) hence  ++*ptr = ++(*ptr)


Now, even if post-increment happens first, remember that post-increment operator returns the old value of ptr in ptr++; and "then only" ptr gets incremented. When the "then-only" happens is not fixed-- it is just guaranteed to happen before the next sequence point. 

selected by

Related questions

4 votes
4 votes
2 answers
1
sh!va asked Jul 16, 2016
1,268 views
In C/C++ an array of pointers is same as(A) Pointer to array(B) Pointer to pointer(C) Pointer to function (D) Pointer to structure
0 votes
0 votes
1 answer
3
mohit chawla asked Sep 18, 2016
560 views
Please help me out guys
4 votes
4 votes
1 answer
4