WEBINAR: On-demand webcast
How to Boost Database Development Productivity on Linux, Docker, and Kubernetes with Microsoft SQL Server 2017 REGISTER >
In the CodeGuru newsletter, I brought up the topic of constant pointers and pointers to constants. While this is a beginning level topic, it is one that some advanced-level people goof up in their code.
Pointer contants and contant pointers are also something that many people simply don't use. If you have a value in your program and it should not change, or if you have a pointer and you don't want it to be pointed to a different value, you should make it a constant with the const keyword.
There are generally two places that the const keyword can be used when declaring a pointer. Consider the following declaration:
char A_char = 'A'; char * myPtr = &A_char;
This is a simple declaration of the variable myPtr. myPtr is a pointer to a character variable and in this case points to the character 'A'.
Don't be confused about the fact that a character pointer is being used to point to a single character—this is perfectly legal! Not every character pointer has to point to a string.
Now consider the following three declarations assuming that char_A has been defined as a type char variable.:
const char * myPtr = &char_A; char * const myPtr = &char_A; const char * const myPtr = &char_A;
What is the difference between each of the valid ones? Do you know?
They are all three valid and correct declarations. Each assigns the addres of char_A to a character pointer. The difference is in what is constant.
The first declaration:
const char * myPtr
declares a pointer to a constant character. You cannot use this pointer to change the value being pointed to:
char char_A = 'A'; const char * myPtr = &char_A; *myPtr = 'J'; // error - can't change value of *myPtr
The second declaration,
char * const myPtr
declares a constant pointer to a character. The location stored in the pointer cannot change. You cannot change where this pointer points:
char char_A = 'A'; char char_B = 'B'; char * const myPtr = &char_A; myPtr = &char_B; // error - can't change address of myPtr
The third declares a pointer to a character where both the pointer value and the value being pointed at will not change.
Pretty simple, but as with many things related to pointers, a number of people seem to have trouble.
# # #