Why Can't a Variable be Changed? - Programming

Changing a variable is a complex question when it comes to object-oriented programming languages like C++. In this article, you'll learn the fundamentals of changing variables, which include the const and lvalue concepts.

What is this "const" before the data type?

const int PI = 3.14159;

const” is a very important qualifier. You should use this qualifier for variables that should never change.


L-value or R-value concept

The following shows some examples:

int X  = 1,  Y = 3;	
X = Y + 1;    // Good		
Y + 1 = X;   // INCORRECT!

The key is for L-value:

  • Variable to be modified must be put on the left side of the “=” operator.
  • Operation expression should be on the right side of the “=” operator.

R-Value:

  • Basically, any other expressions.

Caution: While the following is syntactically correct, it is bad:

whycantvarbechanged.png

Output: X = 20; Y = 20;

Besides, when the compiler produces a warning, you should always review it carefully. Never a good idea to ignore it.