I did not understand why this works:
if(1)
{
int i;
}
and this not:
if(1)
int i;
error: expected expression before int
If you could supply some standard reference.
In C, declarations can only occur as part of a compound-statement, not as part of any of the other kinds of statement (see C11 6.8 and 6.8.2).
This is due to C grammar. Specifically, the if
statement is defined as:
if ( expression ) statement
According to C11 6.8 Statements and blocks, the statement is one of:
labeled-statement
compound-statement
expression-statement
selection-statement
iteration-statement
jump-statement
The declaration can only directly appear in either compound-statement (i.e. delimeted by { ... }
) or as a special case as first expression in for
iteration-statement.
Declaration must be a part of a block-item1.
The block-item-list contains a block-item2.
And the block-item-list can only be inside brackets, as part of a compound-statement3.
This is different in C++, as a declaration-statement is included in statement (the former allows, via a block-statement, defining variables).
(Quoted from ISO/IEC 9899:201x 6.8.2 Compound statement 1)
1
block-item:
declaration
2
block-item-list:
block-item
block-item-list block-item
3
compound-statement:
{ block-item-list opt }
As you can see from section 6.8.2p1 which covers the { ... }
-style example, a declaration is permitted within a compound-statement.
Section 6.8.4p1, however, which covers the syntax for selection statements (i.e. if (...) ...
) doesn't explicitly permit any declarations. In addition, this notation requires an expression, as hinted by the error message, "expected expression ..."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With