Reputation: 21364
When I write something like this:
int data[] = {10,44,56,78,8};
int i = 0;
for(int element : data)
...
that for
is then translated by the compiler in a regular for
? is that for
only a syntactic sugar?
Upvotes: 1
Views: 249
Reputation: 110658
The standard defines the range-based for
statement to be equivalent to:
{
auto && __range = range-init;
for ( auto __begin = begin-expr,
__end = end-expr;
__begin != __end;
++__begin ) {
for-range-declaration = *__begin;
statement
}
}
In your case, range-init
is (data)
, begin-expr
is __range
, end-expr
is __range + 5
, for-range-declaration
is int element
and statement
is ...
. That is, if we substitute all of these, your for
loop is equivalent to:
{
auto && __range = (data);
for ( auto __begin = __range,
__end = __range + 5;
__begin != __end;
++__begin ) {
int element = *__begin;
...
}
}
Whether this translation is actually done by the compiler is an implementation detail. The only thing you can guarantee is that your code will be equivalent to the above code.
Upvotes: 7