Understanding evaluation of expressions containing '++' and '->' operators in C.
- by Leif Ericson
Consider this example:
struct {
int num;
} s, *ps;
s.num = 0;
ps = &s;
++ps->num;
printf("%d", s.num); /* Prints 1 */
It prints 1.
So I understand that it is because according to operators precedence, -> is higher than ++, so the value ps->num (which is 0) is firstly fetched and then the ++ operator operates on it, so it increments it to 1.
struct {
int num;
} s, *ps;
s.num = 0;
ps = &s;
ps++->num;
printf("%d", s.num); /* Prints 0 */
In this example I get 0 and I don't understand why; the explanation of the first example should be the same for this example. But it seems that this expression is evaluated as follows:
At first, the operator ++ operates, and it operates on ps, so it increments it to the next struct. Only then -> operates and it does nothing because it just fetches the num field of the next struct and does nothing with it.
But it contradicts the precedence of operators, which says that -> have higher precedence than ++.
Can someone explain this behavior?
Edit:
After reading two answers which refer to a C++ precedence tables which indicate that a prefix ++/-- operators have lower precedence than ->, I did some googling and came up with this link that states that this rule applies also to C itself. It fits exactly and fully explains this behavior, but I must add that the table in this link contradicts a table in my own copy of K&R ANSI C. So if you have suggestions as to which source is correct I would like to know.
Thanks.