简体   繁体   中英

initialize static char const *somevar

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM