Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading