initialize array with constant number does not work

后端 未结 2 1600
南旧
南旧 2020-12-12 04:59

I get the following error when I use constant nVar instead of a number.

constants.h:

extern const unsigned int nVar;


        
相关标签:
2条回答
  • 2020-12-12 05:41

    I think it happens because compiler should know array's size at compile time, but in your example value of nVar will be known only at linking time due to extern

    0 讨论(0)
  • 2020-12-12 05:55

    Firstly, you are not "initializing" the array with a constant in our example. You are specifying the size of the array. Note that in the given example the array size will be ignored anyway. Your declaration

    void foo(const double q[nVar])
    

    is actually equivalent to

    void foo(const double q[])
    

    and to

    void foo(const double *q)
    

    Secondly, in order for integral constant to be usable in a constant expression it has to be declared with an initializer. In your main.cpp your constant is declared without an initializer, which means that it can't form constant expressions and can't be used in array declarators.

    Unless you really need a const object with external linkage, the proper way to declare your constant would be

    const unsigned int nVar = 5;
    

    right in the header file. Note: no extern and the initializer is specified right in the header file. The definition in constants.cpp has to be removed in that case. Technically, this will create an independent nVar object with internal linkage in each translation unit, but it won't normally occupy any memory unless used as an lvalue.

    0 讨论(0)
提交回复
热议问题