I am going over C and have a question regarding const
usage with pointers. I understand the following code:
const char *someArray
char * const array;
It means that the pointer is constant. Also,
const * const char array;
means a constant pointer to constant memory.
From what is the difference between const int*, const int * const, int const *:
Read it backwards...
int* - pointer to int int const * - pointer to const int int * const - const pointer to int int const * const - const pointer to const int
You should try out cdecl
:
~ $ cdecl Type `help' or `?' for help cdecl> explain const char *someArray declare someArray as pointer to const char cdecl> explain char * const someArray declare someArray as const pointer to char cdecl> explain const char * const s2 declare s2 as const pointer to const char cdecl>
Repeating what other users wrote, but I want to provide context.
Take these two definitions:
void f1(char *ptr) {
/* f1 can change the contents of the array named ptr;
* and it can change what ptr points to */
}
void f2(char * const ptr) {
/* f2 can change the contents of the array named ptr;
* but it cannot change what ptr points to */
}
Making the pointer itself const
, like in the f2 example, is absolutely almost pointless. Every parameter passed to a function is passed by value. If the function changes that value, it only changes its local copy and has no effect on the calling code.
/* ... calling code ... */
f1(buf);
f2(buf);
In either case, buf
is unchanged after the function call.
Consider the strcpy() function
char *strcpy(char *dest, const char *src);
One possible implementation is
char *strcpy(char *dest, const char *src) {
char *bk = dest;
while (*src != '\0') {
*dest++ = *src++;
}
*dest = *src;
return bk;
}
This implementation changes both dest
and src
inside the function only. Making either of the pointers (or both) const
would gain nothing for the strcpy() function or to the calling code.
const char*
is, as you said, a pointer to a char, where you can't change the value of the char (at least not through the pointer (without casting the constness away)).
char* const
is a pointer to a char, where you can change the char, but you can't make the pointer point to a different char.
const char* const
is a constant pointer to a constant char, i.e. you can change neither where the pointer points nor the value of the pointee.
//pointer to a const
void f1()
{
int i = 100;
const int* pi = &i;
//*pi = 200; <- won't compile
pi++;
}
//const pointer
void f2()
{
int i = 100;
int* const pi = &i;
*pi = 200;
//pi++; <- won't compile
}
//const pointer to a const
void f3()
{
int i = 100;
const int* const pi = &i;
//*pi = 200; <- won't compile
//pi++; <- won't compile
}