Q on operator precedence

K

kj

It is my understanding that the subscripting operation has higher
precedence than the direct or indirect selection operation. This
means that an expression like, for example,

s.m[1]

gets parsed as if it were written

s.(m[1])

But the last expression can't possibly make sense, because the
parenthesized subexpression evaluates to data, not to something
like a struct (or union) field.

Therefore, it looks like the compiler has two choices when it comes
across s.m[1]: either be completely correct, and generate an error
whenever it comes across something like s.m[1], or else use some
"common sense" and parse it as (s.m)[1], which at least has some
hope of being correct.

A similar conundrum exists with expressions like

s->t.m

because direct selection (.) has higher precedence than indirect
selection (->). According to the precedence rules, s->t.m should
be equivalent to s->(t.m), but this is nonsensical. In contrast,
the interpretation (s->t).m at least could make sense, but it
violates precedence rules.

I suppose that all of the above could be correct, but it sounds
screwy... What am I missing?

kynn
 
J

jameskuyper

Richard said:
kj said:
It is my understanding that the subscripting operation has higher
precedence than the direct or indirect selection operation. This
means that an expression like, for example,

s.m[1]

gets parsed as if it were written

s.(m[1])

No, . and [] have the same precedence, so it is associativity that
counts. Here, the associativity is left to right, so the parse is
as if the expression were written (s.m)[1].

Whilst it would be possible to prove this from the Standard, I'm
going to duck out and cite p53 of K&R2 instead, because it's
quicker. :)

According to 6.5.2p1, the right operand of a the member selection
operator is required to be an identifier; 'm' is an identifier; m[1]
is a postfix expression. The left operand of the subscript operator is
only required to be a postfix-expression, and s.m is a postfix-
expression, so s.m[1] must be parsed as (s.m)[1].
 
K

kj

In said:
kj said:
It is my understanding that the subscripting operation has higher
precedence than the direct or indirect selection operation. This
means that an expression like, for example,

s.m[1]

gets parsed as if it were written

s.(m[1])
No, . and [] have the same precedence, so it is associativity that
counts.

Thanks, now I see where my misunderstanding came from.

kynn
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,077
Latest member
SangMoor21

Latest Threads

Top