Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring an array whose size is declared as extern const

Tags:

c++

I have a problem initializing an array whose size is defined as extern const. I have always followed the rule that global variables should be declared as extern in the header files and their corresponding definitions should be in one of the implementation files in order to avoid variable redeclaration errors. This approach worked fine till I had to initialize an array with whose size is defined as an extern const. I get an error that a constant expression is expected. However, if I try to assign a value to the const variable the compiler correctly complains that a value cannot be assigned to a constant variable. This actually proves that the compiler does see the variable as a constant. Why then is an error reported when I try to declare an array of the same size?

Is there any way to avoid this without using #define? I would also like to know the reason for this error.

Package.h:

#ifndef PACKAGE_H
#define PACKAGE_H

extern const int SIZE;

#endif

Package.cpp:

#include "Package.h"

const int SIZE = 10;

Foo.cpp:

#include "Package.h"

int main()
{
    // SIZE = 5; // error - cannot assign value to a constant variable
    // int Array[SIZE]; // error - constant expression expected
    return 0;
}
like image 930
psvaibhav Avatar asked Nov 07 '09 14:11

psvaibhav


People also ask

Can an extern be const?

Yes, you can use them together. If you declare "extern const int i", then i is const over its full scope. It is impossible to redefine it as non-const.

Can a variable be used to declare the size of an array?

Declaring Arrays Array variables are declared identically to variables of their data type, except that the variable name is followed by one pair of square [ ] brackets for each dimension of the array. Uninitialized arrays must have the dimensions of their rows, columns, etc. listed within the square brackets.

What does extern const mean?

In a const variable declaration, it specifies that the variable has external linkage. The extern must be applied to all declarations in all files. (Global const variables have internal linkage by default.) extern "C" specifies that the function is defined elsewhere and uses the C-language calling convention.

What is the size of const variable?

An int type has a range of (at least) -32768 to 32767 but constants have to start with a digit so integer constants only have a range of 0-32767 on a 16-bit platform.


2 Answers

The constant is external, so it is defined in another compilation unit (.o file). Therefore the compiler cannot determine the size of your array at compilation time; it is not known until link time what the value of the constant will be.

like image 198
Thomas Avatar answered Oct 26 '22 14:10

Thomas


Well, it sees the variable as const qualified, not as a constant expression.

like image 42
DigitalRoss Avatar answered Oct 26 '22 12:10

DigitalRoss