Using const int as array size

前端 未结 5 692
太阳男子
太阳男子 2020-12-21 18:59

Why am I able to use a locally declared const int as the size of an array declaration but am not allowed to do the same with a const int passed as

5条回答
  •  旧巷少年郎
    2020-12-21 20:00

    1. Array size should be known at compile time.
    2. const mean the value doesn't change.

    So, this is about value of 'dim` at compile time.

    In first case, it is unknown. compiler don't know the value of dim at compile time. It depends on the value passed to the function.

    void f1(const int dim){
      int nums[dim];  // line 2: errors
    }
    

    In this case, dim value is known at compile time, so no issues.

    void f2(){
      const int dim = 5;
      int nums[dim];  // ok
    }
    

    You can use a feature in c++ 11 for this.

    define your function as constexpr.

    constexpr int getDim(......)
    {
        .......
        .......
        return dim;
    }
    

    then call getDim inside f1.

    void f1(){
      int dim = getDim(...); //// computed at compile time
      int nums[dim];
    }
    

    Note that, use of constexpr depend on your application. Further refer this.

提交回复
热议问题