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

In C + +,

char* p = "abc";  // valid in C, invalid in C++

warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings]
Change to the following warning disappears

char* p = (char*)"abc";  // OK

perhaps

char const *p = "abc";  // OK

Reason analysis:

When learning C or C + +, we all know that if the types of variables on both sides of the equal sign are different during the assignment operation, the compiler will perform an operation called implicit conversion to make the variables be assigned.

In the above expression, “ABC” to the right of the equal sign is an invariant constant, which is called string literal in C + +, type is const char *, and P is a char pointer. What happens if you force the assignment?That’s right. We convert the constant coercion type on the right to a pointer. As a result, we are modifying a const constant. The result of compilation will be determined by the compiler and the operating system. Some compilers will pass, some will throw exceptions, and even if they pass, they may be killed because of the sensitivity of the operating system.

This kind of operation of directly assigning string literal to pointer is considered as deprecated by developers, but because many codes have this habit in the past, it is preserved for compatibility

Read More: