for range 循环如何推断普通数组大小
how can a for range loop infer a plain array size
考虑这个片段:
#include <iostream>
int main() {
int s[6] {0, 1, 2, 3, 4, 5};
for ( auto && i: s ) {
std::cout << " " << i << std::endl;
}
}
这可以在 g++ 和 clang++ 下顺利编译和运行。
它在许多帖子中被认为是理所当然的(例如,here and here),但我不清楚编译器如何正确推断 for range
中没有迭代器的类型的数组大小。
任何人都可以回答或在参考中添加 link 吗?
当编译器编译这条语句时
for ( auto && i: s ) {
std::cout << " " << i << std::endl;
它知道变量s
的类型是int[6]
。
因此对于数组,编译器使用 s
和 s + 6
等表达式来定义范围。
根据工作草案[6.5.4/1]:
The range-based for statement
for ( for-range-declaration : for-range-initializer ) statement
is equivalent to
{
auto &&__range = for-range-initializer ;
auto __begin = begin-expr ;
auto __end = end-expr ;
for ( ; __begin != __end; ++__begin ) {
for-range-declaration = *__begin;
statement
}
}
where
[...]
begin-expr and end-expr are determined as follows:
- if the for-range-initializer is an expression of array type R, begin-expr and end-expr are __range and __range + __bound, respectively, where __bound is the array bound. If R is an array of unknown size or an array of incomplete type, the program is ill-formed;
[...]
所以它的工作原理主要是@VladFromMoscow 在他的回答中已经提到了。
考虑这个片段:
#include <iostream>
int main() {
int s[6] {0, 1, 2, 3, 4, 5};
for ( auto && i: s ) {
std::cout << " " << i << std::endl;
}
}
这可以在 g++ 和 clang++ 下顺利编译和运行。
它在许多帖子中被认为是理所当然的(例如,here and here),但我不清楚编译器如何正确推断 for range
中没有迭代器的类型的数组大小。
任何人都可以回答或在参考中添加 link 吗?
当编译器编译这条语句时
for ( auto && i: s ) {
std::cout << " " << i << std::endl;
它知道变量s
的类型是int[6]
。
因此对于数组,编译器使用 s
和 s + 6
等表达式来定义范围。
根据工作草案[6.5.4/1]:
The range-based for statement
for ( for-range-declaration : for-range-initializer ) statement
is equivalent to
{ auto &&__range = for-range-initializer ; auto __begin = begin-expr ; auto __end = end-expr ; for ( ; __begin != __end; ++__begin ) { for-range-declaration = *__begin; statement } }
where
[...]
begin-expr and end-expr are determined as follows:
- if the for-range-initializer is an expression of array type R, begin-expr and end-expr are __range and __range + __bound, respectively, where __bound is the array bound. If R is an array of unknown size or an array of incomplete type, the program is ill-formed;
[...]
所以它的工作原理主要是@VladFromMoscow 在他的回答中已经提到了。