Provide some examples of the const keyword and it’s use with pointers
The const keyword is used when we want to make something – like a variable – have read-only access. Here’s a simple example of the const keyword:
Simple example of the const keyword
const int j = 10;
In our example above, the variable j is declared to use the const keyword. What does this mean? Well, it means that an attempt to change the value of “j” will result in an error.
When using the const keyword with pointers it’s important to note that the real meaning of what’s actually constant changes depending on the exact location of the const keyword.
Pointer to a constant examples
A pointer to a const is a pointer that points to data that is constant. This simply means that you can not change the data that is being pointed to. Here are some examples in code to clarify what we mean by a pointer to a constant:
// this syntax creates a pointer to a const const char* pntr = "constant data"; // this syntax also creates a pointer to a const // but note the syntax is different from example above // although it's exactly the same as the example above char const* pntr = "constant data"; //this will result in an error - //because the data can not be changed *pntr = "test"; //this is OK, because the address can be changed pntr = "testing";
So, a pointer to a constant simply means that it’s a pointer to some constant data. The ‘variable’ holds data that can’t be changed.
Constant pointer examples
With a constant pointer, the address of the pointer itself is constant. But, the variable itself can still change – or the data inside the variable can change, if you want to think of it that way. Here are some examples:
//this is a constant pointer //the address of the pointer can't change //but the data can change char* const pntr = "Some Data"; //this is correct and valid //because the data can still change *pntr = "testing"; //this is incorrect because the address //of the pointer itself can not be changed pntr = "testing";
Constant pointer to a constant example
Think of a constant pointer to a pointer as combination of the two examples presented above. With a constant pointer to a constant, it means that neither the data being pointed to nor the pointer address can be changed. Here’s an example:
//this is a constant pointer to a constant //the address of the pointer can't change //and the data can't be changed const char* const pntr = "Example";