raghu wrote:
John Bode wrote:
sa*****@yahoo.co.in wrote:
Hi Everyone,
>
I often get confused with * and ++ operator when they are used with
pointers as to which would be considered first by the compiler, Can
anyone explain with some examples to understand them easier???
The expression *a++ would be evaluated as follows: *(a++). Here's the
parse tree (best viewed with a monospace font):
unaryexpression
/ \
unaryoperator castexpression
 / \
* postfixexpr ++

primaryexpression

a
As the parse tree shows, the postfix ++ binds to the identifier more
tightly to the identifier than the dereference operator.
The expression ++*a would be evaluated as ++(*a). Here's the parse
tree:
unaryexpression
/ \
++ unaryexpression
/ \
unaryoperator castexpression
 
* primaryexpression

a
The parse tree shows that the deference operator binds more tightly to
the identifier than the prefix ++ operator.
Its not at all clear....still confusing
Doesn't help that the charts got screwed up and don't display right.
Let's try again. Assume the following:
char a[5] = {0, 1, 2, 3, 4};
char *p;
char i;
Assume for the purpose of this example that the address of a is 0x8000,
which means the address of a[1] is 0x8001, a[2] is 0x8002, etc.
Lets start by setting p to point to a[0]:
p = a;
The value of p is 0x8000, and the value of *p is 0. Now we execute the
following statement:
i = *p++;
As I said earlier, the expression *p++ is evaluated as *(p++); the
indirection operator * is being applied to the result of the expression
p++, which evaluates to the current value of p (the side effect of
incrementing p is applied sometime before the end of the statement).
Therefore, after executing that statement, the value of i is 0, the
value of p is 0x8001, and the value of *p is 1.
Now we execute the following statement:
i = ++*p;
In this case, the expression is evaluated as ++(*p); the prefix ++
operator is being applied to the result of the expression *p. Since p
= 0x8001, which is the address of a[1], the result of *p is 1.
Therefore, after executing that statement, the value of i is 2, the
value of p is still 0x8001, but the value of *p is now 2.
As a last case, take the statement
i = *++p;
In this case, the expression is evaluated as *(++p); the indirection
operator is being applied to the result of the expression ++p. Since
the current value of p is 0x8001, the result of ++p is 0x8002, which is
the address of a[2], so the result of *(++p) is 2. After executing
this statement, the value if i is 2, the value of p is 0x8002, and the
value of *p is 2.
So basically, each of the above expressions is evaluated lefttoright.
In the first and third cases (*p++ and *++p), the pointer value is
being incremented, and in the second case (++*p) the value of the thing
being pointed to is being incremented.
Does that help any?