( ) -> operators associativity confused

B

bochengnever

( ) 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
 
E

Eric Sosman

( ) 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'.
 
A

Andrey Tarasevich

(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.
 

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,954
Messages
2,570,116
Members
46,704
Latest member
BernadineF

Latest Threads

Top