0

C-style Arrays are not self-describing as it doesn't has any information about it's size, so for iterating it's elements we need size information somehow. I'm confused as how range-for loop gets the size information. It is expected to fail. Consider 2 conflicting examples,

#include <iostream>
using namespace std;

int main() { 
    int a[] = { 1, 2, 3, 4, 5, 6 };
    for(auto x : a)
        cout<<x<<" ";
    cout<<endl;
    return 0;
}

It ran successfully(unexpected), but

#include <iostream>
using namespace std;

void print_a(int*);

void print_a(int a[])
{
    for(auto x : a)
        cout<<x<<" ";
    cout<<endl;
}
int main() { 
    int a[] = { 1, 2, 3, 4, 5, 6 };
    print_a(a);
    return 0;
}

This produced errors(expected).

Can someone explain as how range-for loop actually works ?

9
  • 3
    "C-style Arrays are not self-describing as it doesn't has any information about it's size" That's not right. It does contain this information (implicitly - it's not stored anywhere, but compiler knows it), but arrays decay to a pointer when passed to a function. Commented Jun 2, 2020 at 14:32
  • @Yksisarvinen but then how actually is range for getting this info about size Commented Jun 2, 2020 at 14:34
  • In the first example, the compiler has visibility that a is an array and of the size of that array, so can work out the range the for loop can iterate over. I assume you don't need an explanation of why the second example doesn't work. Commented Jun 2, 2020 at 14:35
  • 1
    How does the range-based for work for plain arrays? and cppreference for range-based loops. In short, C-style arrays are handled separately when used in range-based for loops. Note that it only works with actual array type, not arrays that decayed to pointers. Commented Jun 2, 2020 at 14:37
  • 3
    The compiler can, however, examine the definition of an array to obtain its size. It can't do that if only given a pointer (which can point to a single value, or to the first of any number of values). Commented Jun 2, 2020 at 14:37

1 Answer 1

-1

range-for loop run from start to end that says it needs to know the length. of statically allocated arrays AKA int array[10] the compiler know the length on compile-time so he knows to terminate them, but on the dynamically allocated array, the compiler doesn't know the length of the array so he cants rang loop them

Sign up to request clarification or add additional context in comments.

1 Comment

That's not entirely true, since statically allocated arrays can decay to pointers and thus lose information about their length. The code in this question is a prime example for this.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.