John
John

Reputation: 911

expression did not evaluate to a constant- 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;
}

Upvotes: 27

Views: 65239

Answers (4)

Amaresh Kumar Sharma
Amaresh Kumar Sharma

Reputation: 743

Well above solutions will work fine with char type. It won't if you had different type e.g. double or float or any other user-defined type for example

double sample_float_array (n+1) //suppose n is a number passed in the functions

to get done what you intended to, and so to be compiled in MSVS you might need to write like below

std::vector <double> sample_float_array;
sample_float_array.resize (n+1);

hope this helps. Cheers

Upvotes: 0

com
com

Reputation: 81

you could use malloc instead of new if you want to use it for C implementation. If you don't you could propably use std::string as @NathanOliver pointed out.

char* ansString; // ********line 10********

ansString = (char*)malloc(sizeOfRetNum*sizeof(char)); // ********line 11********

Upvotes: 0

NathanOliver
NathanOliver

Reputation: 180500

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.

Upvotes: 49

E. Moffat
E. Moffat

Reputation: 3288

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.

Upvotes: 9

Related Questions