Hi, I am learning about constants and I am slightly confused about what I am reading. The sites and book I am using says that a literal, is a constant. So I assume something like int a = 1; is a literal. But I dont understand how that is a constant. I can change that later in code, a = 2; and now 'a' has a different value. But from my understanding, I should not be able to change the value of a constant.
I am obviously confused with something here, but not sure what part I am misunderstanding. If anyone could give me a better way of understanding this, or possibly see what I am not understanding, it would be greatly appreciated
int a = 1; //1 is a literal. a is not const.
const int a = 1; //1 is a literal and a is const. the compiler can change all a's into 1's if it wants, it does not need to go fetch a to get its value like it would a variable. change a now and it is a compiler error.
and newer code uses constexpr instead of const, its a little more flexible.
older code may use #defines, which is C-ish; they don't have a strong type and can be troublesome.
you seem to have overlooked the keywords that make a constant a constant instead of a variable, is all?
The literal value is just representing the value you want stored in the variable. The variable itself is not constant just because the value you copied from was. Consider this:
constint a = 1; // now a actually is constant
int b = a; // but b isn't; it just copied a's value
String literals are different since they are ultimately represented as a constant character pointer that points to the characters in the string literal (which are often stored in "read-only" memory so that writing to them would segfault).
constchar * a = "hello";
char * b = a; // this is not good; compiler should complain