views:

472

answers:

8

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.

A: 

Here you can see that ++ as a prefix has lower priority than ->, but as a postfix it has the same priority as -> and it is evaluated from left to right, so ps++ is done first and then ->.

Edit: this is for C++, not C. So my answer isn't correct.

klew
+4  A: 

The post-increment (ps++) and the pre-increment (++ps) have different associativity in C. The former associates left-to-right whereas the latter associates right-to-left. Check this page out (though this is for C++, so the precedences may be misleading).

In your last example you are changing the pointer to one past the end of &s. You have not changed the value of the pointee. If you need to increment num, you need to bind the ++ to num.

Detailed explanation:

 ps++->num;

A (hypothetical) compiler on seeing this expression, may push the ps object to the stack followed by the ++ operator, the -> operator and finally the object -- num. While evaluationg, where should the compiler start? It looks at the available operators i.e. ++ and ->. Does it choose ps++ or ps? Here precedence rules: since -> has a higher precedence than ++, it takes -> to process with num as one operand and ps as the other operand. So, the value of the expression becomes ps->num i.e. 0 as you rightly observe. What happens to ps after the evaluation? Remember, there is another operator left on the stack? So, the compiler applies this to ps and it now points to one element past &s.

Footnote:

The ANSI/ISO C standard does not use a operator precedence grammar. Rather it uses what is known as a fully-factored grammar. This typically involves an exacting grammar definition dotted with a number of non-terminals like "primary-expression" and "shift-expression" and so on. This is hard to understand, but is easier for the language designer or the compiler vendor. Also, such a grammar is able to encode precedences easily. However, any fully-factored grammar is compatible with an operator-precedence grammar and this is what most books (and websites) do (and also mess up at times).

dirkgently
Leif Ericson
Right, I should have mentioned that.
dirkgently
Leif Ericson
Updated my answer. Hope it helps.
dirkgently
You say that at a certain stage the compiler takes ++ to process with num as one operand, so according to that, we get the operation ++num (or num++, which one should that be?) which is undefined because we cannot refer to num outside it's context (which is the strcut).Also, after the '++' is "wasted" on num how can it be used on ps?
Leif Ericson
Darn, that was a typo. Fixed it. It takes up `->`. Also, there are two things to note: 1) value of the expression and 2) side effects. No operators are wasted since they contribute differently -- in this context, `->` gives you the value and `++` the side-effect.
dirkgently
Thanks, now it is clearer. Sorry I make it hard for you, but who decides that the '++' operates on ps and not on the expression 'ps->num'? Example from arithmetic: if we have -2*3, then '*' has higher precedence than '-', so after the multiplication the '-' operates on the result which is 6 and not on '2'. Why wouldn't that rule apply here?
Leif Ericson
Unary '-' has a higher precedence than *. So, it really is (-2) * 3.
dirkgently
+3  A: 

Even if ++ had a higher priority, this wouldn't change the value -> operates on, as it's a post-increment. See this code that also has another example of this behaviour:

int b = 5;
int a = b++ * 3;
b = 5;
int c = (b++) * 3;

printf("%i, %i\n", a, b, c); // Prints 15, 6, 15

struct {
  int num;
} s, *ps;

s.num = 35;
ps = &s;
printf("%p\n", ps); // Prints the pointer
printf("%i\n", ps++->num); // Prints 35
printf("%p\n", ps); // Prints the increased pointer

printf("%d", s.num); /* Prints 35 */
schnaader
Excellent answer, in my opinion the best of those present now. BTW, from a maximum portability point of view, the ps pointer should be printed using format %p instead of %i.
hlovdal
The prints at line 5 are incorrect. It prints "15, 7, 18". You also forgot one "%i" there. There should be three.
Leif Ericson
Sorry, edited the code and forget to reset b. Now I set b back to 5 to make it work as supposed.
schnaader
+1  A: 

"precedence" is basically a derived property; it follows from parsing rules. ++ps->num is parsed as ++(ps->num) /* () added for clarification of parsing rules */ whereas ps++->num can only be parsed as (ps++)->num.

MSalters
+1  A: 

I guess that is because they have different priority, and within the same group, they have a specific associativity (eg. evaluation order)

Check here. The postfix operator has the same priority as the pointer resolution, but the prefix operator has a lower priority.

Stefano Borini
+1  A: 

ps++->num increments the pointer ps by 1, and then reads the data inside it. Since ps is just after s on the stack, I believe the pointer will most likely be pointing to itself, although this I'm not sure of, and is not important. basically The initial program was doing ++(ps->num) but without the brackets. To achieve the same thing but after you access the data, you would have to do (ps->num)++, or without the brackets: ps->num++.

And since ps is just a pointer, even though you changed its value, s still stays the same.

Michael
+3  A: 

b = ++a; is equivalent to:

a += 1;
b = a;

b = a++; is equivalent to:

b = a;
a += 1;

So it's pretty clear why you don't get the result you look for. The thing you described would be equivalent to (++ps)->num.

Cheery
Nearly equivalent. The technical difference, which I'm sure you knew, is that in the case of b = a++; or b = ++a; a is evaluated only once.
Chris Young
A: 

Precedence is used to resolve ambiguous parsing. ++ps->num could be parsed as ((++ps)->num) or (++(ps->num)); the relative precedence of ++() and -> determines that the latter is the correct parsing.

For ps++->num, there is only one valid parsing: ((ps++)->num), so the precedence of the operators doesn't matter.

outis