语法范围 [英] Range for syntax
问题描述
当我写这样的东西时:
int data[] = {10,44,56,78,8};
int i = 0;
for(int element : data)
...
该 for
然后由编译器以常规的 for
翻译?是 for
只是语法糖?
that for
is then translated by the compiler in a regular for
? is that for
only a syntactic sugar?
推荐答案
该标准将基于范围的 for
语句定义为等同于:
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
}
}
在您的情况下, range-init
是(data)
, begin-expr
是 __ range
, end-expr
是 __ range + 5
, for-range-clarification
是 int元素
和 statement
是 ...
.也就是说,如果我们替换所有这些,则您的 for
循环等效于:
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.
这篇关于语法范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!