Why do I get "forbids converting a string constant to ‘char*’" in C++?

I’m trying to invert the case manually, and I tried this:

char* invertirCase(char* str){
    int size = 0;
    char* iterador = str;
    char* retorno = str;

    while (*iterador != '\0') {

        if (retorno[size] < 96) {
            retorno[size] = *iterador + 32;
        }
        else {
            retorno[size] = *iterador - 32;
        }
        iterador++;
        size++;
    }

    return retorno;
}

I’m trying to figure out where’s the error, but I don’t get it since I’m pretty new at C++ language.

>Solution :

Why do I get "forbids converting a string constant to ‘char*’" in C++?

The error message means that you are trying to pass a string literal to the function.

String literals in C++ have types of constant character arrays that passed by value to functions are implicitly converted to the type const char *. And any attempt to change a string literal results in undefined behavior.

You could pass to the function a character array initialized by a string literal as for example

char s[] = "Hello";
std::cout << invertirCase( s ) << '\n';

In turn the function can be defined the following way

#include <cctype>

char * invertirCase( char *str )
{
    for ( char *p = str; *p; ++p )
    {
        unsigned char c = *p;

        if ( std::isalpha( c )
        {
            if ( std::islower( c )
            {
                *p = toupper( c );
            }
            else
            {
                *p = tolower( c );
            }
        }
    }

    return str;
}

Leave a Reply