AoZ
AoZ

Reputation: 139

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!

Upvotes: 10

Views: 16697

Answers (2)

Jonathan Leffler
Jonathan Leffler

Reputation: 754860

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.

Upvotes: 15

perreal
perreal

Reputation: 98108

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.

Upvotes: 8

Related Questions