Warning: ISO C++ forbids converting a string constant to 'char*' - untypical

Hi!

I have impression that I'm behaving like a cat trying to catch its own tail....

Getting to the point. I have the following construction (flags names as array):

    #define flags_on_number_of_elements 6
    char* flags_on[flags_on_number_of_elements] = { "(name1)", "name2", "name3", "name4", "name5","name6" };
    int flags_on_max_len=0;
    for (int i=0; i<flags_on_number_of_elements; i++) {
    	flags_on_max_len+=strlen(flags_on[i])+1;
    }
    char flags_txt[flags_on_max_len];

It's quite convenient to have them as array as it's embedded device with some statuses and the status value converts directly to the given flag.

However I'm getting warning when compiling:


 warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]

When changing "" to '' I get another problem:

warning: character constant too long for its type

Concluding:

  1. How to avoid those problems?
  2. How to optimise/write better this part of the code?

Please note that statuses names might change and the number of statuses as well...

Should be a const char*.

You will not be able to change the text for each name doing it this way, but you can change the pointer in the flags_on array to point to another name, as long as it is also defined as a const char array.

The flags_on array can be created with as many elements as you like, any unused elements can be set to empty strings.

@david_2018 Are you magician? It works! :grinning_face: Thank you.

Could you explain why it makes the difference?

The text literals "(name1)", "name2", etc, are constant char arrays.
When you create a pointer to a constant, it needs to be declared as const, so that the compiler knows that the pointer should not be used to modify the object that it points to.

The array, flags_on, is not constant. The pointers in the array can be changed to pointers to different constant char arrays, so you could do something like this:

    flags_on[1] = "another name";

If you actually wanted the flags_on array to be constant, it would be declared like this:

    const char* const flags_on[flags_on_number_of_elements] = { "(name1)", "name2", "name3", "name4", "name5","name6" };

If you want to be able to edit the strings themselves, instead of using pointers you can use a two-dimensional array. Note that the second dimension needs to be large enough to hold the largest text that will ever be put into any of the elements, along with an extra character for the terminating null.

    char flags_on[flags_on_number_of_elements][8] = { "(name1)", "name2", "name3", "name4", "name5","name6" };