Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

expression did not evaluate to a constant- c++

Tags:

c++

I wrote the following code for converting a decimal number to base2. not the best one probably, but it worked on eclipse. however, when I try to run it on visual studio, I get this error message on line 10 (emphasized): "expression did not evaluate to a constant". Why is that?

long base2(int number) {
    int remainder, sizeOfRetNum, isNegative = 0;
    if (number<0)
        isNegative = 1;
    int temp = number;
    while (temp != 0) {
        sizeOfRetNum++;
        temp = temp / 2;
    }
    char ansString[sizeOfRetNum]; // ********line 10********
    int j = sizeOfRetNum - 1;
    while (number != 0) {
        remainder = number % 2;
        number = number / 2;
        if (remainder == 0)
            ansString[j] = '0';
        else
            ansString[j] = '1';
        j--;
    }
    long ansNum = atol(ansString);
    if (isNegative == 1)
        ansNum = -ansNum;
    return ansNum;
}
like image 888
John Avatar asked Oct 29 '15 19:10

John


2 Answers

char ansString[sizeOfRetNum]; 

Is a Variable Length Array and is not standard in C++. Some compilers like GCC allow them as an extensions but MSVS will not compile them.

In order to get a dynamic array you will need to use a pointer and new

char* ansString = new char[sizeOfRetNum];

Or better yet, rework the function to use a std::string, which handles the memory management for you.

like image 182
NathanOliver Avatar answered Nov 19 '22 20:11

NathanOliver


sizeOfRetNum is not a constant value - in other words, its value is not known at compile time.

When you want to allocate memory and don't know the value until run time, you need to use dynamic memory allocation. This is done in C++ with operator new. The memory you allocate yourself with new also needs to be freed with delete or delete[].

Change char ansString[sizeOfRetNum]; to char * ansString = new char[sizeOfRetNum];. Don't forget to call delete [] ansString; before the function returns, or you will have a memory leak.

like image 9
E. Moffat Avatar answered Nov 19 '22 20:11

E. Moffat