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])
Related videos on Youtube
Author by
Claudiu
Graduated from Brown University. E-mail: [email protected]
Updated on May 01, 2022Comments
-
Claudiu about 2 years
If I do
*ptr[x]
, is that equivalent to*(ptr[x])
, or(*ptr)[x]
? -
Claudiu almost 14 yearsthat link doesn't mention pointer dereferencing... but it does say array access binds most tightly
-
Justin Ardini almost 14 yearsThe
*
is in the 2nd row of the table, after[]
in the 1st row. -
Justin Ardini almost 14 yearsAh, 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 almost 14 yearsah 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 almost 14 yearswhere does this counterclockwise method come from?
-
Matthew Flaschen almost 14 yearsWikipedia also has a comprehensive C(++)-specific precedence table.
-
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 almost 14 yearsThat'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 almost 14 years@Matthew: Thanks, incorporated this table into my post.
-
Nick T almost 14 yearsSo 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 almost 14 yearsYay, my favorite table. ( en.wikipedia.org/wiki/… )