Shibli
Shibli

Reputation: 6139

initialize array with constant number does not work

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

constants.h:

extern const unsigned int nVar;

constants.cpp:

#include "constants.h"
const unsigned int nVar = 5;

main.cpp

#pragma once
#include "constants.h"
void foo(const double q[nVar])
{
    // ...
}

Compiler:

array constant is not an integer constant before ']' token

expected ')' before ',' token

expected unqualified-id before 'const'

Upvotes: 1

Views: 1144

Answers (2)

AnT stands with Russia
AnT stands with Russia

Reputation: 320381

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.

Upvotes: 1

Evgeny Eltishev
Evgeny Eltishev

Reputation: 603

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

Upvotes: 5

Related Questions