Tuesday, January 18, 2011

error: assignment of read-only location

This error/warning may come you are trying to assign value to a read-only, const variable. To overcome this issue, Always use conditional expression instead of if-else statement while assigning values to const variables.

Please check sample program.

#include

int main()
{
char *test_string = "test";
char *my_string = "my";

const char *string =
test_string?
test_string:
my_string;

/* below code will give error, don't use if-else stmt

const char *string;
if (test_string)
*string = test_string;
else
*string = my_string;
*/

printf("test_string = %s\n",test_string);
printf("my_string = %s\n",my_string);
printf("string = %s\n",string);
}

No comments:

Post a Comment