I have some C++ code that returns this error:

error: assignment of read-only variable ‘parking’

The code:

char const * const parking= "false";

if (phidgets.value(PHIDGET3V_1) > 1000) {
    parking = "true";
} 
else{
    parking = "false";
}

What does this error mean and how do I fix it?

有帮助吗?

解决方案

You declared parking as constant pointer.

char const * const parking= "false";

So it will point only to string literal "false" and may not be changed.

Also this statement

char const * const message = "Value: "+ parking +" ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxy";

is invalid. There is no addition operator for pointers.

其他提示

parking is set to be const (char const * const parking = "false") so it cannot be modified.

When you do parking = "true" it raises compile time error.

How to reproduce the problem very simply to illustrate:

#include <iostream>
int main(){
  const int j = 5;
  j = 7;
}

const means constant, meaning you are not allowed to change it:

error: assignment of read-only variable ‘j’

In your code you set up the parking variable with a const, this is telling the compiler that it will not be modified later. You then modify parking later by setting it to true or false.

Using std::string is far more idiomatic c++ though. So I would do this instead:

  #include<string>
  std::string parking = "false";

  if (phidgets.value(PHIDGET3V_1) > 1000) {
      parking = "true";
      //leds_on(LEDS_RED);
    } else {
      parking = "false";
      //leds_off(LEDS_RED);
    }
std::string message = "Value: "+ parking +" ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxy";

std::string overloads + to do concatenation so it does what you think it does in the last line. Previously you were adding some pointers and that probably doesn't do what you think it does.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top