If I do *ptr[x]
, is that equivalent to *(ptr[x])
, or (*ptr)[x]
?
views:
80answers:
3
+6
A:
*(ptr[x])
See the Wikipedia operator precedence table, or, for a more detailed table, this C/C++ specific table.
Justin Ardini
2010-08-24 01:04:32
that link doesn't mention pointer dereferencing... but it does say array access binds most tightly
Claudiu
2010-08-24 01:06:09
The `*` is in the 2nd row of the table, after `[]` in the 1st row.
Justin Ardini
2010-08-24 01:06:57
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.
Justin Ardini
2010-08-24 01:10:15
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
2010-08-24 01:10:28
Wikipedia also has a comprehensive C(++)-specific [precedence table](http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Operator_precedence).
Matthew Flaschen
2010-08-24 01:14:13
@Matthew: Thanks, incorporated this table into my post.
Justin Ardini
2010-08-24 01:17:34
Yay, my favorite table. ( http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Operator_precedence )
Nick T
2010-08-24 01:37:39
A:
Using the counter-clockwise movement of analyzing and parsing that simple example
1. starting with ptr, work in counter-clockwise until you hit asterisk operator 2. asterisk, in counter-clockwise until you hit subscript operator 3. we arrive here, at subscript operator [x]
Since []
has higher precedence than the asterisk as per this table , that makes it *(ptr[x])
tommieb75
2010-08-24 01:07:34
@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 http://stackoverflow.com/questions/2305255/pointer-array-syntax-char-p-pn-in-c-c
tommieb75
2010-08-24 01:16:24
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.
Steve Jessop
2010-08-24 01:16:48
@Steve: yes, that is how you get to understand which takes precedence...
tommieb75
2010-08-24 01:19:15
@Claudiu: http://www.ericgiguere.com/articles/reading-c-declarations.html
tommieb75
2010-08-24 01:20:18
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
2010-08-24 01:36:03
+2
A:
In C, all postfix operators have higher precedence than prefix operators, and prefix operators have higher precedence than infix operators. So its *(ptr[x])
Chris Dodd
2010-08-24 01:13:31