Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 674
Sabrina Avatar asked Feb 21 '17 02:02

Sabrina


Video Answer


4 Answers

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

like image 65
Kerrek SB Avatar answered Nov 05 '22 22:11

Kerrek SB


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.

like image 32
Grzegorz Szpetkowski Avatar answered Nov 05 '22 21:11

Grzegorz Szpetkowski


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 }

like image 21
2501 Avatar answered Nov 05 '22 22:11

2501


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

like image 34
autistic Avatar answered Nov 05 '22 21:11

autistic