Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: Beginner
Jan 2, 2001

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.h
extern const int ID_LENGTH; // declaration

// in const.cpp
const 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.h
const int ID_LENGTH=1024; // declaration becomes definition
                          // linkage type changed as well

Danny Kalev
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date