0

I am really confused what is exactly const in const char is because i can change the value. Is the Pointer const or what is this? and what is the difference to const char or char* or char const???

3

3 Answers 3

2
char * p = ... 

is a pointer to a char. You can change the pointer, as well as the value the pointer is pointing to.

char const * p = ... const char * p = ... 

are equivalent, and are pointers to a char const. The pointer can be pointed anywhere, but it must always point to a char const.

char const * const p = ... const char * const p = ... 

are equivalent, and declare a const pointer to a char const. You can't change what the pointer is pointing to, or the value at what the pointer is pointing to.

char * const p = ... 

is a const pointer to a char. You can change the value that is pointed to, but you can't change the pointer to point somewhere else.

Sign up to request clarification or add additional context in comments.

Comments

1

I am really confused what is exactly const in const char

The char is const. I.e. the pointed type is const char.

because i can change the value.

Indeed, the pointer is not const, therefore it can be made to point elsewhere by changing its value.

Is the Pointer const

No. It is a non-const pointer to const.

and what is the difference to const char

It is a non-mutable character.

or char*

It is a pointer to a character.

or char const???

Same as const char.

Comments

0

No, you can't change the value.

const char* ptr = "thing"; ptr[2] = 'o'; // error 

It's a pointer to const chars.

You can, however, make the pointer point to something else, because it's not a const char* const. :)

Const applies to the left, unless there's nothing there, in which case it applies to the right.

1 Comment

thanks for the help, it makes things clear

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.