C - why convert main () argument to const
(I'm new to C, maybe my question isn't very smart, but I did google before I ask.)
I saw the following code in git source code:
int main(int argc, char **av) {
const char **argv = (const char **) av;
// ... more code ...
}
It converts char ** av to const char ** argv , I thought it meant that the argument is immutable, but I wrote a program and that argv and argv [i] are mutable.
Question 1 : What is the purpose and goodness of this line of code?
Question 2 : What is the behavior of a const pointer? I did google but didn't find a good answer.
@Update
I am testing more according to the answers and it seems that argv [i] [j] is immutable, but argv and argv [i] are mutable.
So the constant on the pointer makes the original value immutable, but the pointer itself is still changed.
So my guess is that the main purpose of the code from git is also to prevent the original arguments from being changed.
testing code :
#include <stdio.h>
int main(int argc, char * av[]) {
// modify value pointed by a non-const pointer - ok
av[0][0] = 'h';
printf("argv[0] = %s\n", av[0]);
// modify const pointer itself - ok
const char **argv = (const char **) av;
argv[0] = "fake";
printf("argv[0] = %s\n", argv[0]);
char *arr[] = {"how", "are", "you"};
argv = (const char **)arr;
printf("argv[0] = %s\n", argv[0]);
// modify the value itself which is pointed by a const pointer - bad, an error will be thrown,
/*
argv[0][0] = 'x';
printf("argv[0] = %s\n", argv[0]);
*/
return 0;
}
The current code can compile and run without warning or error, but if it doesn't comment out the two commented lines at the end, then it will throw the following error when compiled:
error: assigning read-only space '** argv
source to share
In practice, this is not very useful here (and the generated code won't change much if the compiler is optimizing ).
However, argv
unchanged, so the compiler, for example, would catch the assignment as an error as
argv[1][0] = '_'; // wrong
A const
thing cannot be assigned. Therefore a pointer const
cannot be assigned, and a pointer to const
means that the dereference pointer is a location that cannot be assigned. (and you can mix both: have a pointer const
to const
)
BTW, main
-in standard C99 is a very special feature. You cannot declare it in an arbitrary way (it should almost always be declared int main(int, char**)
or int main(void)
....), and you may not be able to call it (for example, it cannot be recursive), but that might be different in C and C ++ Thus, the ad int main (int, const char**)
would be illegal.
source to share