How can a for range loop infer the size of a simple matrix

Consider this snippet:

#include <iostream>

int main() {
  int s[6] {0, 1, 2, 3, 4, 5};
  for ( auto && i: s ) {
    std::cout << " " << i << std::endl;
  }
}

This compiles and runs happily under both g ++ and clang ++.
This is taken for granted in many posts ( here and here , for example), but it is not clear to me how the compiler can correctly determine the size of an array in for rangefor a type without an iterator.
Can someone answer or add link to link?

+4
source share
2 answers

In accordance with the working draft [ 6.5.4 / 1 ]:

Range Based Operator

for ( for-range-declaration : for-range-initializer ) statement

equivalently

{
  auto &&__range = for-range-initializer ;
  auto __begin = begin-expr ;
  auto __end = end-expr ;
  for ( ; __begin != __end; ++__begin ) {
      for-range-declaration = *__begin;
      statement
  }
}

Where

[...]

begin-expr end-expr :

  • for-range-initializer R, begin-expr end-expr: __range __range + __bound , __bound - . R - , ;

[...]

, @VladFromMoscow .

+5

  for ( auto && i: s ) {
    std::cout << " " << i << std::endl;

s, int[6].

, s s + 6 .

+4

All Articles