initialize array size from another array value

后端 未结 3 1467
难免孤独
难免孤独 2020-12-18 09:48
#include 
using namespace std; 

const int vals[] = {0, 1, 2, 3, 4}; 

int newArray[ vals[2] ]; //\"error: array bound is not an integer constant\"

         


        
3条回答
  •  抹茶落季
    2020-12-18 10:27

    Unfortunately you can't do that in standard C++ because vals[2] is not a constant expression! In the coming standard you would have constexpr(implemented in g++ 4.6) to request compile-time evaluation easily:

    #include 
    using namespace std; 
    
    constexpr int vals[] = {0, 1, 2, 3, 4}; 
    
    int newArray[ vals[2] ]; // vals[2] is a constant expression now!
    
    int main(){
        return vals[2];
    }
    

提交回复
热议问题