Tim Martin
Tim Martin

Reputation: 3697

How is this C++ expression interpreted as an invocation?

In "Inside the C++ Object Model", the author gives the following example of code that is potentially ambiguous, requiring the parser to look ahead to resolve it:

...if C++ were to throw off the C declaration syntax, lookahead would not be required to determine that the following is an invocation of pf rather than its definition:

// don’t know if declaration or invocation 
// until see the integer constant 1024 
int ( *pf )( 1024 );

He implies that this is interpreted as an invocation of the function pf. I can't see what the declaration of pf could be to make this a valid invocation.

Upvotes: 0

Views: 127

Answers (2)

Joseph Mansfield
Joseph Mansfield

Reputation: 110698

It's an ugly declaration of an int* called pf being initialized with the value 1024. However, this conversion is not valid without an explicit cast:

int ( *pf )((int*)1024);

So the line given in the question is equivalent to:

int* pf = 1024;

To understand why, consider that int ((((*pf)))); is the same as int* pf;. You can put as many parentheses as you like around the declarator.

In a declaration T D where D has the form
( D1 )
the type of the contained declarator-id is the same as that of the contained declarator-id in the declaration
T D1
Parentheses do not alter the type of the embedded declarator-id, but they can alter the binding of complex declarators.

I cannot see any reason that this would be considered a function invocation. Especially considering that it begins with int. I can see how it could possibly be a declaration of a function pointer until it sees the integer literal. If for example, it had been this:

int ( *pf )(int);

This would be a declaration of pf of type pointer to function returning int and taking a single argument of type int.

Upvotes: 2

spin_eight
spin_eight

Reputation: 4025

int ( *pf )( int); - it is declaration

Upvotes: 2

Related Questions