What's the difference between the following three pointer declarations in C:
void * const myPointer1;
void const *myPointer2;
const void *myPointer3;
And which one is used to prevent:
myPointer = somethingElse;
What's the difference between the following three pointer declarations in C:
void * const myPointer1;
void const *myPointer2;
const void *myPointer3;
And which one is used to prevent:
myPointer = somethingElse;
Read the rules from right to left:
void * const myPointer1;
myPointer1 is a const pointer to void.
void const *myPointer2;
myPointer2 is a pointer to a const void.
const void *myPointer3;
myPointer3 is a pointer to a void const.
Conclusions:
myPointer1 is what you are looking for -- it's a const pointer, so its value cannot be modifiedmyPointer2 and myPointer3 are the same thingmyPointer2 and myPointer3 are kind of meaningless -- dereferencing a void* does not make senseIn some places, you can put the const in front of whatever is declared const:
const int * x; // pointer to constant int
You can always put the const after whatever is declared const:
int const * x; // pointer to constant int
int * const x; // constant pointer to int
int const * const x; // constant pointer to constant int
Hence, my personal recommendation, always have the const trailing, because that's the only "rule" that can be adhered to consistently.
myPointer1 is a const pointer to void. mypointer2 and myPointer3 are both pointers to const void.The difference between myPointer2 and myPointer3 declarations is just a matter of style.
NB: const void means here that the pointed data is const. Nothing to do with void from int main(void) for instance.
void * const myPointer1; = declare myPointer1 as const pointer to voidvoid const *myPointer2; = declare myPointer3 as pointer to void constconst void *myPointer3; = declare myPointer3 as pointer to const voidWhenever in such kinda doubts, you can use:: cdecl.org
You should try myPointer1 to avoid the condition you explained as it is a const pointer.