C ++ 11 re-allocation in a loop

This code compiles in Visual Studio 2015 update 3 (and here: the C ++ visual compiler on the Internet , and not in other compilers I tried online (GCC and CLANG), which gives a re-publishing error

vector<int> v = {1,2,3};
for (auto i : v) {
  printf("%d ", i);
  int i = 99;
  printf("%d ", i);
}

: 1 99 2 99 3 99

The VS C ++ online compiler (version: 19.10.24903.0) warns about this:

warning C4456: declaration 'i' hides previous local declaration

Is there any place in the C ++ 11 specification so that both versions are valid?

It seems to me that VS2015 creates an area for "auto i" and an internal area for the body of the loop.

Adding an extra area, as suggested by a colleague, compiles in other compilers that I tested (not that I wanted this, it's just for curiosity):

vector<int> v = {1,2,3};
for (auto i : v) {{
  printf("%d ", i);
  int i = 99;
  printf("%d ", i);
}}

thank

EDIT: , , , "Angew" , , VS .

: cpp

:

for ( range_declaration : range_expression ) loop_statement

:

{
 auto && __range = range_expression ; 
 for (auto __begin = begin_expr, __end = end_expr; 
  __begin != __end; ++__begin) { 
    range_declaration = *__begin; 
    loop_statement
 } 
} 

, loop_statement - , , , , .

2: , , - (cpp for loop) :

for ( init-statement condition(optional); iteration_expression(optional) ) statement

" , :"

{
   init_statement 
   while ( condition ) { 
     statement 
     iteration_expression ; 
   }
}

, , / statement , , , , , - . .

+4
2

N4606 ( ++ 17) 3.3.3 basic.scope.block, 4

, INIT-, - , , , , , , , ( ), ( , ) ; . 6.4

:

, ... -range-declaration... ... ...

, , .

+5

- ++ 11, ?

.

, :: . , , .

0

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


All Articles