Problem.
The alarm deprecated conversion from string constant to char*
is usually given when trying to store text literal whose type is constant pointer to char
, in a variable that is pointer to char
(without being constant).
You can also find this alarm when you try to store a constant pointer to char
on a pointer to% co_of non-constant%.
Examples.
void funcion(char *texto);
// deprecated conversion from string constant to char*
funcion("Patatas fritas, que ricas!");
In the previous code we see how a text literal ( char
) is stored in a variable of type pointer to "Patatas fritas, que ricas!"
without the qualifier char
. The text literal type is const
(constant array of 27 elements of type const char[27]
), this type of arrays is implicitly convertible to constant pointer to char
; when passing it to non-constant pointer the alarm appears. To correct the problem add the char
qualifier to the parameter:
void funcion(const char *texto); // const anyadido
funcion("Patatas fritas, que ricas!"); // ninguna alarma
It can also happen if the return of a function is const
and it is stored in a variable pointer to const char *
that does not have the qualifier char
:
struct C { const char *miembro() { return nullptr; } };
void funcion(char *texto);
C c;
// deprecated conversion from string constant to char*
funcion(c.miembro());
Why is it happening ?: Compatibility with c
The implicit conversion of const
to const char *
is the only conversion of that type allowed in C ++, it exists for backward compatibility with C.
In the C language, the semantics of the text literals and the char *
qualifier are different than in C ++. In C a text literal is an array of const
non-constant while in C ++ a text literal is an array of char
constant. To allow the same semantics in C that in C ++ this conversion was marked as an alarm instead of as an error.
Thus, in C, passing a text literal to a function is allowed:
// Si compilamos con C en lugar de con C++ ...
void funcion(char *texto);
// ... esto no da problemas ni alarmas.
funcion("Patatas fritas, que ricas!");
However, conversions of qualified data with char
to data without qualification is explicitly prohibited in C ++:
// Funcion que recibe un puntero a char
void funcion(char *texto);
// Funcion que recibe un puntero a int
void funcion_int(int *números);
// Un arreglo de valores int.
const int numeros[]{0,1,2,3,4,5,6,7,8,9};
// deprecated conversion from string constant to char*
funcion("Patatas fritas, que ricas!");
// Error! NO se puede convertir 'const int *' a 'int *'.
funcion_int(numeros);
While with const
we get the deprecated alarm with char
we get an error. If you use more modern C ++ compilers you will get an error instead of an alarm.