Sunday, January 24, 2021

The C++20 for-each range differences, part III

With the C++20, there is a new capability that helps when the index is still needed within the loop:

1
2
3
4
5
6
7
8
int main()
{
  const char buffer[]{"buffer"};
  for(int i = 0; const auto & c : buffer)
  { 
    ++i; 
  }
}


The generated source code is then:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
int main()
{
  const char buffer[7] = {"buffer"};
  {
    int i = 0;
    char const (&__range1)[7] = buffer;

    const char * __begin1
        = static_cast<const char *>(__range1);

    const char * __end1
      = static_cast<const char *>(__range1) + 7L;

    for(; __begin1 != __end1; ++__begin1) 
    {
      const char & c = *__begin1;
      ++i;
    }
  }
}


[keywords: for loop, for-each range, c++98, c++11, c++14, c++17, c++20]

No comments:

Post a Comment