EmiliOrtega EmiliOrtega - 4 years ago 75
C Question

const char variable why does it work if I modify it?

I have the following code

int main(int argc, char **argv, char **envp)
{
const char *usuario= NULL;
while(*envp)
{
char *str = *envp++;
//if(strcmp(str,"USERNAME")==0)
if(str[0] == 'U' && str[1] == 'S' && str[2]=='E' && str[3]=='R' && str[4] == 'N')
{
usuario = str;
break;
}
}
if(usuario != NULL)
{
printf("Hola, bienvenido al programa %s",usuario);
}
return 0;
}


And my question is, why is it working? That "usuario" variable was defined as NULL is of CONST type. It's assumed that those variables can't be modified throughout the program, but then within the while it was modified by
usuario = str;

Answer Source

usuario is not constant in this case.

Tip: Pointer declarations must be read from right to left

Try reading

const char *usuario= NULL;

from right to left, in this case, usuario is a pointer to constant char

To declare usuario as constant, do

const char * const usuario= NULL;

Above code snippet will make usuario constant.

Try reading above code snippet from right to left, in this case, usuario is a constant pointer to a constant char

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download