Order of operations for dereference and bracket-ref in C

13,452

Solution 1

*(ptr[x])

See the Wikipedia operator precedence table, or, for a more detailed table, this C/C++ specific table.

Solution 2

In C, all postfix operators have higher precedence than prefix operators, and prefix operators have higher precedence than infix operators. So its *(ptr[x])

Share:
13,452

Related videos on Youtube

Claudiu
Author by

Claudiu

Graduated from Brown University. E-mail: [email protected]

Updated on May 01, 2022

Comments

  • Claudiu
    Claudiu about 2 years

    If I do *ptr[x], is that equivalent to *(ptr[x]), or (*ptr)[x]?

  • Claudiu
    Claudiu almost 14 years
    that link doesn't mention pointer dereferencing... but it does say array access binds most tightly
  • Justin Ardini
    Justin Ardini almost 14 years
    The * is in the 2nd row of the table, after [] in the 1st row.
  • Justin Ardini
    Justin Ardini almost 14 years
    Ah, I see how this could be confusing, since * could mean multiplication or pointer dereference. Multiplication goes after though, in row 3 of the table.
  • Claudiu
    Claudiu almost 14 years
    ah yes, reading comprehension for the win. i was scanning the text for mention of the word 'pointer' and didn't realize it's just a unary operation too.
  • Claudiu
    Claudiu almost 14 years
    where does this counterclockwise method come from?
  • Matthew Flaschen
    Matthew Flaschen almost 14 years
    Wikipedia also has a comprehensive C(++)-specific precedence table.
  • t0mm13b
    t0mm13b almost 14 years
    @Claudiu: It's a well known technique for parsing and analyzing C expressions...it is found in 'Expert C Programming - Peter Van der Linden', see stackoverflow.com/questions/2305255/…
  • Steve Jessop
    Steve Jessop almost 14 years
    That's for parsing type specifiers and declarations. But in the question *ptr[x] is an expression, and so all you need to know is operator precedence.
  • Justin Ardini
    Justin Ardini almost 14 years
    @Matthew: Thanks, incorporated this table into my post.
  • Nick T
    Nick T almost 14 years
    So the counter-clockwise thing doesn't apply to expressions? I would strongly drop mentioning that, as operator precedence is all that matters here.
  • Nick T
    Nick T almost 14 years
    Yay, my favorite table. ( en.wikipedia.org/wiki/… )