By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
449,079 Members | 916 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 449,079 IT Pros & Developers. It's quick & easy.

( ) -> operators associativity confused

P: n/a
( ) and -are left to right in the same order . eg:
struct foo
{
int a ;
void * p;
}

main()
{
struct foo* A= malloc(sizeof(struct foo));
(char*)A->p;
}
(char*)A->p I think should be a compiler error,because (char*)A evalute
first ,now A come be a pointer to char ,so A do not have a field of p .
But it compiled successfully.So A->p first evaluted,
it seem to conflict to the associativity of () and -.

thank you

Oct 25 '06 #1
Share this Question
Share on Google+
2 Replies


P: n/a
bo**********@gmail.com wrote:
( ) and -are left to right in the same order . eg:
struct foo
{
int a ;
void * p;
}

main()
{
struct foo* A= malloc(sizeof(struct foo));
(char*)A->p;
}
(char*)A->p I think should be a compiler error,because (char*)A evalute
first ,now A come be a pointer to char ,so A do not have a field of p .
But it compiled successfully.So A->p first evaluted,
it seem to conflict to the associativity of () and -.
-has higher precedence than ("binds more tightly than")
(type). Associativity is not by itself a complete description
of the syntax.

In fact, both precedence and associativity are just verbal
conveniences. The language's syntax is defined by a BNF grammar
that parses `(char*)A->b' as

cast-expression
::= ( type-name ) cast-expression
::= ( char* ) cast-expression
::= ( char* ) unary-expression
::= ( char* ) postfix-expression
::= ( char* ) primary-expression - identifier
::= ( char* ) identifier - identifier
::= ( char* ) A - identifier
::= ( char* ) A - b

In the transition from the first line to the second, you can see
that `(char*)A->b' divides into the two pieces `(char*)' and
`A->b', not into `(char*)A' and `->b'.

--
Eric Sosman
es*****@acm-dot-org.invalid

Oct 25 '06 #2

P: n/a
bo**********@gmail.com wrote:
(char*)A->p I think should be a compiler error,because (char*)A evalute
first ,now A come be a pointer to char ,so A do not have a field of p .
But it compiled successfully.So A->p first evaluted,
it seem to conflict to the associativity of () and -.
...
I don't know where you found such strange "associativity", but normally in C
postfix operators have higher priority than prefix operators, meaning that
'(char*) A->p' is interpreted as '(char*) (A->p)' and, therefore, should compile.

--
Best regards,
Andrey Tarasevich
Oct 25 '06 #3

This discussion thread is closed

Replies have been disabled for this discussion.