Ambiguities in Statements


There is a circumstance where the grammars of expressions and declarations are indistinguishable. An expression statement in which the left most subexpression is a function-style type cast is grammatically indistinguishable from a declaration where the first declarator begins with a left parenthesis. To distinguish between an expression statement and a declaration in such circumstances, the entire statement may require examination. Examining the statement in its entirety resolves the ambiguity in many cases.

Consider the following examples:

T(i)->j = 7;     // is an expression statement - casts i to T and assigns 7 to member j
T(i)++;          // is an expression statement - casts i to T and post increments T
T(i) << j;       // is an expression statement - casts i to T and left shifts by j
 
T(m);            // is a declaration - m is an instance of T, as in  T m;
T(*pf)();        // is a declaration - pf is a pointer to a function returning T
T(a)[];          // is a declaration - a is an array of T as in  T a[];

The details of the type involved are not significant (beyond the fact that it is indeed a type name); thus, the process of interpreting the statements and distinguishing between expression statements and declarations is entirely a syntactic one.

A slightly different ambiguity between expression statements and declarations is avoided by requiring the return type of a function to be explicitly specified when declaring a function within a block. For example:

void f()
{
 int g();  // function declaration
 g();      // expression statement
 
 int i;    // integer declaration
 i;        // expression statement
}