Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 774
AoZ Avatar asked Jan 11 '13 05:01

AoZ


People also ask

What is a static const char * in C++?

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).

What is a char * const?

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.

What is const char * str?

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....

Can const char * be reassigned?

Variables defined with const cannot be Reassigned.


2 Answers

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.

like image 166
Jonathan Leffler Avatar answered Oct 29 '22 17:10

Jonathan Leffler


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.

like image 31
perreal Avatar answered Oct 29 '22 15:10

perreal