Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference among (const char *str) , (char const *str) and (char *const str)? [duplicate]

Possible Duplicate:
What is the difference between char * const and const char *?
const char * const versus const char *?

as we define a function in c,we may use (const char *str) , (char const *str) or (char *const str) as a variable.What's the difference among them?

like image 624
Alex Avatar asked Dec 04 '22 14:12

Alex


2 Answers

The first two are equivalent, const char *str and char const *str both declare str to be a pointer to a char constant (that means that the char itself shouldn't be modified), the third one, char *const str declares str to be a constant pointer (meaning that once assigned it shouldn't be changed) to a char (which itself can be modified freely).

An interesting article regarding how to read type declarations is here, in case you want to check it.

like image 200
lccarrasco Avatar answered Dec 21 '22 23:12

lccarrasco


char const * str and const char * str are the same, as const applies to the term on its left or, if there isn't a type on the left side, to the right one. That's why you get a double const error on const char const *. Both are pointers on a constant char. You can change the value of the pointer, but not the dereferenced value:

const char * my_const_str;
my_const_str = "Hello world!"; // ok
my_const_str[0] = "h"; // error: my_const_str[0] is const!

char * const on the other hand is a constant pointer. You cannot change the pointer, but you can change the value dereferenced by the pointer.

char * const my_const_ptr = malloc(10*sizeof(char));
my_const_str[0] = "h"; // ok
my_const_str = "hello world"; // error, you would change the value of my_const_str!
like image 26
Zeta Avatar answered Dec 22 '22 01:12

Zeta