what dose "const char const* var" mean?

S

s88

Hi all:
I saw the code likes...

7 #include <stdio.h>
8 int main(void){
9 const char *const green = "\033[0;40;32m";
10 const char *const normal = "\033[0m";
11 printf("%sHello World%s\n", green, normal);
12 return 0;
13 }

what's the different between "const char *green" and "const char *const
green"???
Thank you!
 
M

Michael Mair

s88 said:
Hi all:
I saw the code likes...

7 #include <stdio.h>
8 int main(void){
9 const char *const green = "\033[0;40;32m";
10 const char *const normal = "\033[0m";
11 printf("%sHello World%s\n", green, normal);
12 return 0;
13 }

what's the different between "const char *green" and "const char *const
green"???

const char *green (or, equivalently, char const *green) points to
char and you cannot modify the pointed to object using green,
i.e.
const char *green = "verde";
green = "gruen";
is okay, but
green[0] = 'V';
strcpy(green, "Gruen");
are not allowed.

char *const green is a constant pointer to char, so you cannot modify
green but you can modify the object green points to.
char buf[42];
char *const green = buf;
strcpy(green, "verde");
green[0] = "V";
is okay, but
char *const green = buf;
green = "gruen";
is not allowed.

const char *const green = "gruen"; gives you a constant pointer to
const char, i.e. green will always point to the address where the
string "gruen" starts and cannot be used to change that string.

Cheers
Michael
 
R

ranjeet.gupta

Michael said:
s88 said:
Hi all:
I saw the code likes...

7 #include <stdio.h>
8 int main(void){
9 const char *const green = "\033[0;40;32m";
10 const char *const normal = "\033[0m";
11 printf("%sHello World%s\n", green, normal);
12 return 0;
13 }

what's the different between "const char *green" and "const char *const
green"???

const char *green (or, equivalently, char const *green) points to
char and you cannot modify the pointed to object using green,
i.e.
const char *green = "verde";
green = "gruen";
is okay, but
green[0] = 'V';
strcpy(green, "Gruen");
are not allowed.

char *const green is a constant pointer to char, so you cannot modify
green but you can modify the object green points to.
char buf[42];
char *const green = buf;
strcpy(green, "verde");
green[0] = "V";
is okay, but
char *const green = buf;
green = "gruen";
is not allowed.

Just to add:

const char *const green = "Verde";
In this you can't change any thing.

Regards
Ranjeet
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,173
Latest member
GeraldReund
Top