Monday, September 23, 2013

const char * vs char * const

I came across the question 'What is the difference between const char * vs char * const many times. After trying several sample programs, here is a simple way to understand the differences. Let us see what char * means:
char * p; // defines a buffer where characters can be stored
          // returns a pointer that is pointing to the first element in the buffer and is denoted by p

When const is applied on char *, depending on the position of const,
different things happen on the buffer+pointer.
const char * p ->  buffer contents are a constant. Pointer variable p can be modified to point to a different buffer.
char * const p ->  buffer contents can be modified. Pointer variable p cannot be modified. p points to the same location, all the time.
const char * const p -> means that the buffer and the pointer cannot be modified

Summary:
DefinitionBufferPointer
const char * pCannot changeCan change
char * const pCan changeCannot change
const char * const pCannot changeCannot change

No comments:

Post a Comment