title=deprecated conversion from string constant to 'char*'

From Wikibooks, open books for an open world
< GCC Debugging‎ | g++‎ | Warnings
Jump to navigation Jump to search


Initializing a character pointer variable with a string literal[edit]

In standard C, string literals have type char *, even though they cannot be modified without invoking undefined behavior (risking a program crash or data corruption). g++ issues a warning to let you know that you are relying on this behavior.

char *x = "foo bar";

Solution 1: Change the "char *" to "const char *"

Most programmers assign all string literals to a pointer of type const char *, which ensures that they cannot be accidentally written to.

const char *x = "foo bar";

Solution 2: Use a string object instead of a character pointer

string x = "foo bar";

Solution 3: Cast the string literal to type "char *"

char *x = (char *)"foo bar";


  • Message found in GCC version 4.5.1