Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ error: assignment of read-only variable [closed]

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?

like image 759
mxmolins Avatar asked Oct 15 '25 17:10

mxmolins


2 Answers

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.

like image 186
Vlad from Moscow Avatar answered Oct 18 '25 06:10

Vlad from Moscow


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’
like image 25
Gabriel Avatar answered Oct 18 '25 06:10

Gabriel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!