Search code examples
c++arraysvisual-c++dimension

const variable not recognized as array dimension


long AnsiString::pos(const char* plainString) const {
const size_t patternLength = strlen(plainString);
if (patternLength == 0) return -1;

size_t stringLength = count;
int partialMatch[patternLength]; // int* partialMatch = new int[patternLength];

KMPBuildPartialMatchTable(plainString, partialMatch);

int currentStringCharacter = 0;
int currentPatternCharacter = 0;
while (currentStringCharacter < stringLength) {
    if (currentPatternCharacter == -1) {
        currentStringCharacter++;
        currentPatternCharacter = 0;
    }
    else if (items[currentStringCharacter] == plainString[currentPatternCharacter]) {
        currentStringCharacter++;
        currentPatternCharacter++;
        if (currentPatternCharacter == patternLength) return currentStringCharacter - currentPatternCharacter;
    } else {
        currentPatternCharacter = partialMatch[currentPatternCharacter];
    }
}

// delete(partialMatch);

return -1;
 }

I get an error in the implementaation of this claas method using visual c++.

int partialMatch[ patternLength ] ; // expression must have a constant value 

(I'm using VS in other language so you could find some differences).

I declared patternLength as a constant as you can see. A solution is commented in the ccode but i don't want to use dynamic memory allocation. Some idea ?


Solution

  • Array sizes must be known at compile time.

    A const variable does not ensure that. The const qualifier ensures that the variable cannot be modified once it is initialized.

    It is possible for the value of const variable to be known at compile time. If a compiler can detect that, then the variable can be used to define the size of an array.

    More often, the value of a const variable is not known at compile time. It is initialized with a value at run time, which can't be changed after the variable is initialized. That does not make it fit for use to define the size of an array.

    If you want to be able to use the variable at compile time, use constexpr instead. The compiler will do its best to evaluate the value at compile time. It will fail if the value of the variable cannot be evaluated at compile time.