Range for loops in C ++

It would seem that the syntax style "for everyone", available in C ++ 11, allows iteration of the array without knowing the actual size of the array (the number of elements). I assume that since it is part of the new standard, it is absolutely safe even for C-arrays. Generally, you should know the size of the C array separately before manipulating it, but I want those who have tested this new C ++ technique to have a check that it works exactly as you expected:

extern float bunch[100];

for (float &f : bunch) {
  f += someNumber;
}

Is there anything I should know about the unobvious side effects or disadvantages of this technique? This is not very noticeable in the code that I see, probably because most of the code was written before it was in the standard. Want to make sure that its rare use is not related to some other reason, not known.

+5
source share
3 answers

There is nothing strange or unsafe in this use. The size of the array is known at compile time, so it can be used in a loop. This is an example of a template function that lets you know the length of an array:

template< class T, std::size_t N >
std::size_t length( const T (&)[N] )
{
  return N;
}

Foo f[5];
std::cout << length(f) << "\n";

This should make it clear that you cannot use this method or range-based loops for type C arrays with dynamic size.

, , , std::array ( , ti std::tr1 boost), C-:

extern std::array<float, 100> bunch;

for (auto &f : bunch) {
  f += someNumber;
}
+4

for-loop . , , :

float* array = new float[100];
for (float& f : array) {
    // ...
}

. . , , .

+4

Arrays can be passed as links and infer their type and length.

#include <iostream>

template<typename T, size_t N>
void fun(T const (&arr)[N])
{
    for (std::size_t i = 0; i < N; ++i)
       std::cout << arr[i] << " ";
}

int main()
{
   int x[] = { 1, 2, 3 }; // no need to set length here
   fun(x); // 1 2 3, no need to specify type and length here
}
+2
source

All Articles