I have been looking at a source code, and i came across this code
static char const *const delimit_method_string[] =
{
"none", "prepend", "separate", NULL
};
I thought I knew the meaning of const
keyword in the C language but after seeing this syntax I am confused as I can't decode the meaning of the syntax, so I wanted to know the meaning of using const
like this I searched internet I saw some questions like this in stackoverflow that are,
But still I don't understand what's the meaning of the syntax in that code snippet, may be that because I am not good enough with fundamentals of C but I really like to improve it.
So I wrote some code to know how that syntax works, this is what I tried:
#include <stdio.h>
int main()
{
char a = 'A';
char b = 'B';
char const * const ptr = &a;
ptr = &b;
printf("a is %c\n", *ptr);
printf("a is %c", a);
return 0;
}
I got this output, that somewhat I expected.
$ gcc test.c
test.c: In function 'main':
test.c:9:13: error: assignment of read-only variable 'ptr'
9 | ptr = &b;
|
^
I changed the code and tested again,
#include <stdio.h>
int main()
{
char a = 'A';
char b = 'B';
char const const *ptr = &a;
ptr = &b;
printf("a is %c\n", *ptr);
printf("a is %c", a);
return 0;
}
this time the output is not what I expected,
$ ./a.exe
a is B
a is A
I really appreciate if someone can explain what is the correct way of using const
in C and also how the syntax in first code snippet works.
static char const *const delimit_method_string
:delimit_method_string
is aconst
pointer*
which points to aconst
((unmodifyable)char
, which isstatic
. This helps me understand it. – Fiske