Sabrina
Sabrina

Reputation: 1466

lone declaration in if statement?

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.

Upvotes: 5

Views: 158

Answers (5)

autistic
autistic

Reputation: 15642

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

Upvotes: 2

2501
2501

Reputation: 25753

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 }

Upvotes: 3

Grzegorz Szpetkowski
Grzegorz Szpetkowski

Reputation: 37944

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.

Upvotes: 3

Bill Drissel
Bill Drissel

Reputation: 186

The first code example declares an int visible only inside an otherwise empty scope ... hard to see the utility! The second apparently attempts to conditionally? declare an int visible in the enclosing (function?) scope. Hard to imagine the utility of such a conditional declaration ... would it require run-time re-compilation?

Upvotes: 0

Kerrek SB
Kerrek SB

Reputation: 477150

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

Upvotes: 6

Related Questions