You can declare constant variables. Here is an example:
const int var = 9;You can also declare pointers which are constant. But we must distinguish between two types of constant pointers.
const a = 34;
const int * ptr2Const; //something which points to a constant!
ptr2Const = &a;
int a = 34;int * const constPtr points to a single memory location, it can never be changed once it is assigned.
int * const constPtr = &a;
Let us remeber something about constants. When you create a regular constant you must inialize it at the time when you declare it. If you try to initialize it later, you will get a compiler error. This is because the compiler has no way to know that you are not attempting to change the value of a constant. You think you are setting the value for the first time, but the compiler just sees that you are assigning it a new value, and that is not allowed.
const int A;For the same reason, you must initialize a constant pointer when you declare it, as I did above. Just like it would be pointles to create a constant variable and not initialize at the time of declaration because then you could never use it for anything, so too would it be pointles to create a constant pointer variable and not initialize it.
A = 10; //compiler error
//rather you must do this
const int A = 10;
int * const constPtr;// pointless, constPtr can never serve any useful purpose
Let's see some examples in code that are based on the above principles.
© Nachum Danzig December 2017