Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
157 views
in Technique[技术] by (71.8m points)

c++ - Range-for-statement cannot build range expression with array function parameter

Why cannot build range expression passing an array as a function argument and using in a range-for-statement. Thanks for the help

void increment(int v[]){
    // No problem
    int w[10] = {9,8,7,6,5,4,3,2,1,9};
    for(int& x:w){
        std::cout<<"range-for-statement: "<<++x<<"
";
    }

    // error: cannot build range expression with array function 
    // parameter 'v' since parameter with array type 'int []' is 
    // treated as pointer type 'int *'
    for(int x:v){
        std::cout<<"printing "<<x<<"
";
    }

    // No problem
    for (int i = 0; i < 10; i++){
        int* p = &v[i];             
    }
}

int main()
{
    int v[10] = {9,8,7,6,5,4,3,2,1,9};
    increment(v);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Despite appearances, v is a pointer not an array - as the error message says. Built-in arrays are weird things, which can't be copied or passed by value, and silently turn into pointers at awkward moments.

There is no way to know the size of the array it points to, so no way to generate a loop to iterate over it. Options include:

  • use a proper range-style container, like std::array or std::vector
  • pass the size of the array as an extra argument, and interate with an old-school loop

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...