user3393571
user3393571

Reputation: 101

Read-only variable is not assignable

Yes this is for homework, my code is asking me to enter an array that is terminated upon typing in the number 0 or when it reaches the maximum number of integers ARRAY_SIZE so when I type in my code the line array[num_elements]=i; returns an error that states Read-only variable is not assignable.

void read_list(const int array[], int & num_elements) {
    int i(1);

    cout<<"Enter list of "<< ARRAY_SIZE<<" integers (ending with 0)";

    while (i != 0 && num_elements < ARRAY_SIZE) {
        cin >> i;
        array[num_elements] = i;
num_elements++;
    }

}

Upvotes: 3

Views: 23873

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 310980

You are using constant reference to access elements of the array. You may not assign these elements using a constant reference. So you need to remove qualifier const from the parameter declaration.

Also the code of the function is wrong. For example it does initialize num_elements and assigns 0 to the last element of the array.

The function should look the following way

int read_list( int array[], int max_size ) 
{
    int i = 0;
    int x;

    std::cout<<"Enter list of no more than " << max_size << " integers (0 - exit): ";

    while ( i < max_size && std::cin >> x && x != 0 ) 
    {
        array[i++] = x;
    }

    return i;
} 

And it can be called as

int num_elements = read_list( YourArray, ARRAY_SIZE );  

Upvotes: 1

mic_e
mic_e

Reputation: 5830

Well, your array's fields are read-only variables, so you can't assign values to them.

Remove the const qualifier, and it should work fine.

I'm unsure whether array[num_elements] = num_elements++ does something useful, though. Maybe you wanted to do array[num_elements++] = i instead?

Upvotes: 9

Related Questions