Single declaration in if statement?

I did not understand why this works:

if(1) { int i; } 

and this is not:

 if(1) int i; 

error: expected expression before int

If you can provide a standard link.

+5
source share
5 answers

In C, declarations can only be executed as a compound statement, and not as part of any other expression (see C11 6.8 and 6.8.2).

+7
source

The declaration must be part of block 1 .

The list of block elements contains a block element 2 .

And the list of element blocks can only be inside the brackets, as part of compound statement 3 .

In C ++, this is different because the statement statement is included in the statement (the first allows variables to be defined using the block statement).


(Quoted from ISO / IEC 9899: 201x 6.8.2 Compound Application 1)

1 block point:
declaration

2 block-item-list:
block point
item list block

3 compound expression:
{block-item-list opt}

+4
source

This is related to grammar C. In particular, the if is defined as:

if (expression) statement

According to C11 6.8. Expressions and blocks, the operator is one of:

labeled approval
compound statement
statement expressions
select-expression
iterative-expression
jump statement

An ad can only appear in a compound statement (ie delimeted by { ... } ) or as a special example as the first expression in a for iterative statement.

+4
source

As you can see from section 6.8.2p1 , which covers an example of the style { ... } , the declaration is allowed in its component part, the statement.

Section 6.8.4p1 , however, which covers the syntax for select statements (i.e. if (...) ... ), does not explicitly allow any declarations. In addition, the expression indicated by the error message is required for this notation, " expected expression ... "

+3
source

The first code example declares an int visible only inside an empty area ... it's hard to see the utility! The second, apparently, is trying conditionally? declare int visible in the scope (function?). It is hard to imagine the usefulness of such a conditional declaration ... would it require recompilation at run time?

0
source

Source: https://habr.com/ru/post/1264480/


All Articles