Home > Software engineering >  C what does the error of "Initial value of reference to a non-const must be an lvalue" m
C what does the error of "Initial value of reference to a non-const must be an lvalue" m

Time:11-24

I am a complete beginner to C and was assigned to write a function that returns the factors of a number. Below, I have included the function I also created called print_vector that will print all of the elements of a vector to the Console.

In my assignment, in order to check if the factorize function is working, we have to use the test_factorize function provided, which I have also included. However, the issue I've run in to is that the given test_factorize does not work due to the error "Initial value of reference to a non-const must be an lvalue." I'm unsure what this means and why the test_factorize runs into an issue because the output of factorize is a vector and the input of print_vector is also a vector, so I don't see why the contents of test_factorize result in an error, though I suspect it might be something within the `factorize' function I defined that causes this error.

#include <iostream>
#include <vector>

using namespace std;

void print_vector(std::vector<int>& v) {
    for (int i = 0; i < v.size(); i  ) {
        cout << v[i] << " ";
    }
    cout << endl;
}

std::vector<int> factorize(int n) {
    std::vector<int> answer;
    for (int i = 1;i < n   1;   i) {
        if (n % i == 0) {
            answer.push_back(i);
        }
    }
    return answer;
}

void test_factorize() {
print_vector(factorize(2));
print_vector(factorize(72));
print_vector(factorize(196));
}

CodePudding user response:

The error is from this line:

void print_vector(std::vector<int>& v) {

Since you didn't include the const keyword in the argument-type, you are (implicitly) indicating that print_vector has the right to modify the contents of v.

However, you are calling print_vector() with a temporary object (the vector returned by factorize()) as an argument, and C doesn't allow you to pass a temporary object by non-const reference, presumably on the theory that making changes to a temporary object is pointless (because the temporary is going to be destroyed as soon as the function call returns, so any changes made to it would have no effect) and therefore must a programmer error.

In any case, the fix is easy, just change your function declaration to this:

void print_vector(const std::vector<int>& v) {

... and that will allow you to pass a reference-to-a-temporary-vector to it.

  • Related