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;
}
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.
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.
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.
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.
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.
Well, it sees the variable as const qualified, not as a constant expression.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With