code analysis
-
Hi, #include int main() { char str[20] = "Hello"; char *const p=str; *p='M'; printf("%s\n", str); return 0; } output: Mello As per my knowledge when we use const then we can't change a char in t then how output is Mello instead of Hello.
-
Hi, #include int main() { char str[20] = "Hello"; char *const p=str; *p='M'; printf("%s\n", str); return 0; } output: Mello As per my knowledge when we use const then we can't change a char in t then how output is Mello instead of Hello.
You need to read the declaration right to left:
char *const p=str;
| | | |
| | | +- the variable p
| | +----- is a constant
| +---------pointer
+------------to a characterSo
const
here applies to the pointer p and not to the data that it is pointing to. That would be:const char* p=str; // p is a pointer to a character constant.
-
Hi, #include int main() { char str[20] = "Hello"; char *const p=str; *p='M'; printf("%s\n", str); return 0; } output: Mello As per my knowledge when we use const then we can't change a char in t then how output is Mello instead of Hello.
const
applies to what's on its immediate left: a pointer (*
) or a type (char
and many others, even ones that you've defined). If there's nothing on its left--that is, when it appears first--const
applies to what's on its immediate right.Robust Services Core | Software Techniques for Lemmings | Articles
The fox knows many things, but the hedgehog knows one big thing. -
You need to read the declaration right to left:
char *const p=str;
| | | |
| | | +- the variable p
| | +----- is a constant
| +---------pointer
+------------to a characterSo
const
here applies to the pointer p and not to the data that it is pointing to. That would be:const char* p=str; // p is a pointer to a character constant.
Hi Richard, Thank you for your reply. I understood the concept clearly. Best Regards Niharika
-
const
applies to what's on its immediate left: a pointer (*
) or a type (char
and many others, even ones that you've defined). If there's nothing on its left--that is, when it appears first--const
applies to what's on its immediate right.Robust Services Core | Software Techniques for Lemmings | Articles
The fox knows many things, but the hedgehog knows one big thing.Hi Greg, Thank you for your immediate response. I understood the point clearly. Regarda, Niharika