Hello! Here, actually the question about C ++: declared the variable int in the first for loop, and in the second loop the IDE does not see it and gives an error, saying that it is not declared? It suggests that this is not a bug, but a feature. So it should be? Is the variable declared in the loop visible only for this loop? Screenshot with an error

  • rather yes than no. But I will not say the exact answer according to the standard) - pavel

2 answers 2

According to the description of for-clauses in the C ++ standard (6.5.3 The for statement)

1 The for statement

for ( for-init-statement conditionopt; expressionopt) statement 

is equivalent to

 { for-init-statement while ( condition ) { statement expression ; } } 

It is not necessary to declare that it will be a statement. [Note: Thus the statement statement speci fi es initialization for the loop; the condition (6.4) can be taken; the expression often incrementing it is done after each iteration. —End note]

Therefore, your for clause can be represented as described in the standard.

 { // блок кода, в котором объявлена переменная i int i = 0; { while ( i < 10; ) { massiv[i] = i; i++; } } } // здесь уже нет доступа к переменной `i` в виду прекращения ее существования. 

After exiting the for clause, the variable ceases to exist, and the corresponding name becomes undeclared.

    Variables in C ++ are visible within the block in which they are declared. In your case, i is declared in the for block, and therefore is only visible in it. The second for block tries to assign i the value 0, when the variable i is no longer there. In each block, redeclare the variable.

     for (int i = 0; i < 7;++i) //здесь i есть ++i; //А здесь нету i = 0; //ошибка