I am reading a piece of code, in which there is
#include ...
static char const *program_name;
...
int main(int argc, char** argv){
program_name = argv[0];
...
}
I am wondering how can the main function assign value to a const
variable. Any help would be appreciated!
const char* is a pointer to a constant char, meaning the char in question can't be modified. char* const is a constant pointer to a char, meaning the char can be modified, but the pointer can not (e.g. you can't make it point somewhere else).
char* const says that the pointer can point to a char and value of char pointed by this pointer can be changed. But we cannot change the value of pointer as it is now constant and it cannot point to another char.
The const char *Str tells the compiler that the DATA the pointer points too is const . This means, Str can be changed within Func, but *Str cannot. As a copy of the pointer is passed to Func, any changes made to Str are not seen by main....
Variables defined with const cannot be Reassigned.
The declaration:
static char const *program_name;
says program_name
is a (variable) pointer to constant characters. The pointer can change (so it can be assigned in main()
), but the string pointed at cannot be changed via this pointer.
Compare and contrast with:
static char * const unalterable_pointer = "Hedwig";
This is a constant pointer to variable data; the pointer cannot be changed, though if the string it was initialized to point at was not a literal, the string could be modified:
static char owls[] = "Pigwidgeon";
static char * const owl_name = owls;
strcpy(owl_name, "Hedwig");
/* owl_name = "Hermes"; */ /* Not allowed */
Also compare and contrast with:
static char const * const fixed_pointer_to_fixed_data = "Hermes";
This is a constant pointer to constant data.
program_name
is a pointer to const char, not a const pointer. The assignment statement assigns a value to the pointer not to the pointee.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With