devxlogo

Using const Variables to Define the Size of an Array

Using const Variables to Define the Size of an Array

C++ requires that the size of an array be a constant integral expression. However, the following code refuses to compile:

 // in const.hextern const int ID_LENGTH; // declaration// in const.cppconst int ID_LENGTH=1024; // definition// in main.cpp#include int main(){ char id[ID_LENGTH];  // compilation error }


There are two problems with this code. First, the value of the constant ID_LENGTH isn’t known when the compiler sees the definition of the array in main.cpp. Because of this, the compiler cannot compute the array’s size. Secondly, the declaration and definition of ID_LENGTH are incompatible: while the declaration says that ID_LENGTH has external linkage, in the definition, ID_LENGTH is implicitly defined as having static (i.e., file-scope) linkage. To fix this, you can remove the extern specifier from the declaration and change it to a definition by initializing the constant:

 // in const.hconst int ID_LENGTH=1024; // declaration becomes definition                          // linkage type changed as well

See also  Professionalism Starts in Your Inbox: Keys to Presenting Your Best Self in Email
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist