Fix C++ "invalid conversion from 'const char*' to 'char*'" — Add const, Copy the Text, or Own It in std::string
Read-only text met a pointer that promises write access. This guide separates the three ways the error arrives — a const variable, a string literal, and c_str() — and matches each one to its repair: add const where nothing modifies the text, copy into an array where something does, own the text in std::string where it must stay mutable, and keep const_cast for the single legacy case where it is actually safe.
Written November 22, 2026 · Tested with GCC 13.3.0 · 23 min read
- The rule underneath: conversions may add const, never remove it
- The first failure: a const variable assigned to char
- The second failure: a string literal assigned to char, and why GCC words it differently
- The third failure: read-only text passed to a char parameter
Written November 22, 2026
Tested with GCC 13.3.0
What this guide is
A char* and a const char* differ by one word, and that word is a promise. A const char* points to characters the code may read but must not modify through that pointer. A char* points to characters the code is allowed to modify. Converting the first into the second would manufacture write permission out of read permission, with no change to the underlying characters at all — the same bytes, suddenly writable on paper. C++ does not allow that conversion implicitly, and the title error is the compiler refusing it: invalid conversion from 'const char*' to 'char*'.
The refusal matters because the text behind a const char* is often genuinely read-only. A string literal names an object with static storage duration whose modification is undefined behavior. The array returned by std::string::c_str() belongs to the string, and writing to it is undefined behavior. A variable the programmer declared const may point at either of those, or at storage some other part of the program is relying on staying unchanged. If the compiler quietly dropped the const, every one of those protections would become a convention instead of a rule, and the first function that actually wrote through the pointer would corrupt text it had no right to touch — or crash, if the text lives in read-only storage. The error is early, cheap, and exact. Treat it as a question the compiler is asking about your design: does anything in this code actually need to write to these characters? Almost always the answer is no, and the fix is to say so.
This guide works through the error in the order that separates its causes. First, the clean form of the title error: a const char* variable assigned to a char*. Second, the string-literal form, which GCC reports with different wording — and, by default, only as a warning — for a historical reason worth understanding, because code that merely warns today is still wrong. Third, the function-argument form, where the same conversion is attempted at a call site, and the c_str() form, where the read-only pointer comes out of a std::string. Then the four fixes, in the order to reach for them: add const when nothing writes; copy the text into a local array when a callee really writes and the text is short-lived; store the text in a std::string and use its data() when the text must be owned, mutable, and longer-lived; and use const_cast only for the narrow legacy case where the underlying object is genuinely mutable and the receiving API, despite its char* parameter, does not write. The guide closes with the -fpermissive trap — the flag that downgrades this error to a warning and thereby deletes the protection — a decision table, and a checklist.
Build every program in this guide with g++ -std=c++17. Nothing here needs a newer standard; the one fix that depends on a standard version, the non-const std::string::data(), arrived in C++17 and is called out where it appears.
The rule underneath: conversions may add const, never remove it
Implicit conversions between pointer types follow a one-way rule. A char* converts implicitly to a const char*: handing writable text to read-only code discards a capability, which can never surprise the owner of the text, so the language allows it without a cast. The reverse — a const char* converting to a char* — adds a capability the source never granted, so no implicit conversion exists for it. GCC's error names exactly the two types involved, in source-to-target order: from 'const char*', the type you have, to 'char*', the type the context requires. When you read this error, read it as a sentence: somewhere, code that is allowed to write is about to receive characters that were only promised for reading.
Two consequences of the one-way rule shape everything below. The first is that the error is always fixable from either side, and choosing the side is the whole decision. You can change the receiving side to accept const char* — correct when the receiver never writes — or you can change the supplying side so that it genuinely owns writable characters — correct when writing really happens. Every fix in this guide is one of those two moves, or the explicit, narrow exception to them. The second consequence is that the error is contagious in a useful direction: if a function's parameter is char*, every caller holding read-only text fails at the call; fixing the parameter to const char*, when the function body never writes, repairs all of those call sites at once and documents, in the signature, a fact about the function that was true all along.
One more distinction prevents a common misreading. In const char* p, the const qualifies the characters, not the pointer: p itself can be reassigned to point elsewhere, but *p cannot be assigned through p. The mirror spelling, char* const p, makes the pointer itself unchangeable while leaving the characters writable — a different promise, and not the one in this error. The error is always about the characters. When GCC underlines the argument and annotates it const char* in the diagnostic, it is pointing at the character-level qualification that the target type lacks.
The first failure: a const variable assigned to char*
The smallest program that produces the title error word for word is three lines long. A const char* is initialized from a literal — that step is fine, and it is how literals are meant to be held — and the value is then assigned to a char*:
int main() {
const char* name = "hello";
char* p = name;
return p[0] == 'h' ? 0 : 1;
}
$ g++ -std=c++17 -g -Wall -Wextra -o fail_const_var fail_const_var.cpp
fail_const_var.cpp: In function 'int main()':
fail_const_var.cpp:3:15: error: invalid conversion from 'const char*' to 'char*' [-fpermissive]
3 | char* p = name;
| ^~~~
| |
| const char*
Read the diagnostic in its parts. The headline names the conversion that was attempted and refused, from 'const char*' to 'char*'. The source line and the caret span mark the initializer, name — the exact expression whose type does not fit. The annotation underneath, const char*, restates the type of that expression, so there is no doubt about which side carries the qualification. The trailing [-fpermissive] is a label, not part of the complaint: it names the compiler flag that would downgrade this error to a warning. It does not mean the flag is in use, and it does not mean the code is nearly correct — it is GCC noting that this particular diagnostic belongs to the family its permissive mode relaxes. Leave that flag alone; the section near the end of this guide shows what accepting its offer actually does.
Note what is not in the error. The first line of the program, initializing a const char* from the literal "hello", earns no diagnostic at all, because it asks for exactly the access a literal offers: reading. The failure is entirely in the second step, where the read-only view is asked to become a writable one. Nothing about the characters changed between the two lines; only the claimed permission changed, and the permission is what the type system tracks. This is also why the error survives every attempt to route around it with an intermediate variable of the same read-only type, a function returning const char*, or a conditional expression whose result is const char*: the types, not the spelling of the route, decide.
If your real code looks like this program — a variable declared char* out of habit, holding text that the rest of the function only reads — the repair is a single word on the declaration, covered as the first fix below. Keep reading only if your char* exists because something downstream demands one. That demand, stated by a function signature, is the next failure.
The second failure: a string literal assigned to char*, and why GCC words it differently
Replace the two-step version with the one-liner most programmers meet first — a literal assigned directly to a char* — and GCC's answer changes, in both wording and severity:
int main() {
char* p = "hello";
return p[0] == 'h' ? 0 : 1;
}
$ g++ -std=c++17 -g -Wall -Wextra -o fail_literal fail_literal.cpp
fail_literal.cpp: In function 'int main()':
fail_literal.cpp:2:15: warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]
2 | char* p = "hello";
| ^~~~~~~
Two facts in this transcript deserve attention, because both are easy to get wrong from memory. The first is the severity: with the ordinary build command, this is a warning, and the program compiles and links. A build that treats warnings as noise will ship this code. The second is the wording: GCC does not call this an invalid conversion from const char*. It reports a distinct, older diagnostic — ISO C++ forbids converting a string constant to 'char*' — tagged [-Wwrite-strings], because the literal case has its own history and its own warning class.
The history explains both facts. An ordinary string literal such as "hello" has type const char[6] — an array of six constant characters, the five letters plus the terminating null — and it names an object with static storage duration. That has been the literal's type since C++11 without exception. Before C++11, the language carried a deliberate compatibility concession for C code: string literals were convertible to char*, a deprecated conversion that existed so pre-const C APIs could be called from C++ without casts everywhere. C++11 removed that conversion. Since then, a literal is not convertible or assignable to a non-const char* at all; an explicit cast is required if such a conversion is genuinely wanted. GCC, however, still classifies its diagnostic for this specific pattern as the -Wwrite-strings warning rather than a hard error, as a concession to the volume of old code it would otherwise break outright. Ask GCC to enforce the standard strictly and the same line becomes an error with the same wording:
$ g++ -std=c++17 -pedantic-errors -g -Wall -Wextra -o fail_literal_p fail_literal.cpp
fail_literal.cpp: In function 'int main()':
fail_literal.cpp:2:15: error: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]
2 | char* p = "hello";
| ^~~~~~~
The practical conclusions are three. Do not conclude, from the warning's mildness, that the literal form is a lesser offense than the const char* form: both attempt to claim write access to read-only characters, and in the literal case the characters are the literal's own, whose modification is undefined behavior — arguably the more dangerous of the two. Do not conclude, from the different wording, that you are looking at a different problem: search your build log for both messages, because a codebase can carry the hard error at call sites and the warning at declarations at the same time. And do not silence the warning by giving the variable the type the literal actually has and moving on without checking the rest of the function — the declaration const char* p = "hello"; is correct and complete only if nothing later writes through p, passes p to a char* parameter, or returns p into a context that expects writability. The warning marks the first place the promise was broken, not necessarily the only one.
There is one neighboring declaration that looks similar and is not this error at all: char buf[] = "hello";. Initializing a character array from a literal copies the literal's characters, including the null, into a new, ordinary, writable array owned by the declaration. No conversion of the literal to a pointer is involved, the copy is a special initialization rule for character arrays, and the result is fully mutable. That declaration is not a workaround to apologize for — it is the second fix in this guide, and the right answer whenever a writable, short-lived copy of known text is what the code needs.
The third failure: read-only text passed to a char* parameter
In real code the conversion is attempted at a call far more often than at a declaration. A function written — usually inherited, or written before its author thought about const — with a char* parameter rejects every read-only argument, and GCC reports the title error at each call site:
#include <iostream>
void print_label(char* text) {
std::cout << text << '\n';
}
int main() {
const char* name = "status";
print_label(name);
print_label("ready");
return 0;
}
$ g++ -std=c++17 -pedantic-errors -g -Wall -Wextra -o fail_const_arg_p fail_const_arg.cpp
fail_const_arg.cpp: In function 'int main()':
fail_const_arg.cpp:9:17: error: invalid conversion from 'const char*' to 'char*' [-fpermissive]
9 | print_label(name);
| ^~~~
| |
| const char*
fail_const_arg.cpp:3:24: note: initializing argument 1 of 'void print_label(char*)'
3 | void print_label(char* text) {
| ~~~~~~^~~~
fail_const_arg.cpp:10:17: error: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]
10 | print_label("ready");
| ^~~~~~~
This transcript was produced with -pedantic-errors, so both call sites appear as errors; under the ordinary build command the first call is the same hard error and the second is the -Wwrite-strings warning from the previous section. The substance is identical either way, and the transcript shows the family's two wordings side by side, which is why the stricter command is the one quoted here.
Read the first error's note as carefully as the error itself. After naming the conversion, GCC adds initializing argument 1 of 'void print_label(char*)' and points into the function's declaration, underlining the parameter. That note is the compiler telling you where the requirement comes from: argument passing is initialization, the parameter is initialized from the argument, and a char* parameter cannot be initialized from a const char* argument for the same reason the variable in the first failure could not be. The call site is where the error is reported; the parameter declaration is where the requirement was created. When the function is yours and its body never writes through the parameter — print_label only streams the text — the correct edit is in the declaration the note points to, not at any of the calls. One word there, and both call sites in this program, the variable and the literal alike, become valid unchanged.
When the function is not yours — a library or C API whose signature you cannot change — the note is equally useful, read the other way: the requirement is real and external, and the work moves to the supplying side. What you owe the call is genuinely writable characters with a lifetime that covers the call. The array-copy fix and the std::string fix below are the two honest ways to supply them, chosen by how long the writable text must live.
Notice, finally, what the function body contributes to the diagnosis. GCC does not inspect print_label's body and soften the error because the body happens not to write. The type system works from declarations, deliberately: the signature is the contract every caller must be able to trust without reading the implementation, and a char* parameter is a contract that says writing may happen. If the contract overstates what the function does, fix the contract. If it states the truth, respect it at the call.
The fourth failure: the result of c_str() assigned to char*
The third common source of read-only text is a std::string asked for its C-style view. c_str() returns a pointer to a null-terminated character array holding the string's contents — and its return type is const char*, in every standard, with no non-const overload. Assigning its result to a char* is the title error again:
#include <string>
int main() {
std::string s = "hello";
char* p = s.c_str();
return p[0] == 'h' ? 0 : 1;
}
$ g++ -std=c++17 -g -Wall -Wextra -o fail_cstr fail_cstr.cpp
fail_cstr.cpp: In function 'int main()':
fail_cstr.cpp:5:22: error: invalid conversion from 'const char*' to 'char*' [-fpermissive]
5 | char* p = s.c_str();
| ~~~~~~~^~
| |
| const char*
The const in this return type is load-bearing in two directions. Outward, it protects the string's internal representation: the array c_str() points into is the string's own storage, and writing to the character array accessed through c_str() is undefined behavior — a write could change a character the string's size and invariants assume, plant a null in the middle of the contents, or overwrite the terminating null the string maintains after its last character. Inward, it protects the reader of the code: a const char* obtained from c_str() advertises that the characters are a view, valid only while the string lives and is not modified — the pointer is invalidated if the string is passed by non-const reference to a standard library function or if a non-const member function other than a small excluded set is called on it. A char* would advertise the opposite of both facts.
The fix for this form depends, as ever, on whether writing is real. If the char* exists only because a downstream function demands one and never writes, the call belongs through the const-correct route — change that function's parameter if it is yours. If the text genuinely must be modified as a C string while the std::string owns it, c_str() is simply the wrong accessor: since C++17 the non-const overload of data() returns a char* into the same storage, legally writable across the string's contents. That is the third fix below, and the c_str() failure is its most common doorway.
The const-object variant is worth seeing once, because it forecloses a tempting shortcut. On a const std::string, even data() returns const char* — the const overload is the only one a const object offers — and the assignment fails identically:
#include <string>
int main() {
const std::string s = "hello";
char* p = s.data();
return p[0] == 'h' ? 0 : 1;
}
$ g++ -std=c++17 -g -Wall -Wextra -o fail_const_data fail_const_data.cpp
fail_const_data.cpp: In function 'int main()':
fail_const_data.cpp:5:21: error: invalid conversion from 'const char*' to 'char*' [-fpermissive]
5 | char* p = s.data();
| ~~~~~~^~
| |
| const char*
A const string's characters are as read-only as a literal's, and for the same reason: the qualification describes the object, not the accessor you chose. If text held in a const string truly needs modification, copy it into a non-const string or an array first — supply-side ownership again — rather than reaching for a cast.
Fix 1: declare const char* when nothing modifies the text
The first fix is the common one, and it is a fix of declarations, not of data. Audit every place the text flows: the variable that holds it, each parameter it passes through, and each return value that carries it. Wherever nothing assigns through the pointer — no writes to its elements, no call handing it to a function that writes — the type should be const char*. Applied to both failing programs above, the declarations change and nothing else does:
#include <iostream>
void print_label(const char* text) {
std::cout << text << '\n';
}
int main() {
const char* name = "status";
print_label(name);
print_label("ready");
const char* p = "hello";
std::cout << p << '\n';
return 0;
}
$ g++ -std=c++17 -g -Wall -Wextra -o fixed_const_param fixed_const_param.cpp
$ ./fixed_const_param
status
ready
hello
Three outputs, and each one certifies a call or assignment that failed before. The const char* variable now passes to the const char* parameter with no conversion at all — identical types. The literal "ready" passes directly: a literal decays, when a pointer is needed, to a pointer to its first element, and that pointer is a const char*, so it initializes a const char* parameter exactly. And the literal assigned to the const char* variable p is the literal's intended use, earning no warning under any flag combination used in this guide.
Why this fix ranks first is worth stating plainly, because its cheapness can make it look like a way of merely pleasing the compiler. It is the opposite: it is the fix that makes the code say what was already true. If no code writes through the pointer, then char* was a false statement about the program — a standing offer of write access that any future edit could have taken up without any further diagnostic, including an edit that wrote into a literal. Changing the declaration removes that standing offer everywhere the text travels, at zero runtime cost: const on a pointer's pointee changes no generated access, copies no characters, and allocates nothing. It also widens what the function can accept from then on — a const char* parameter takes literals, const variables, c_str() results, and ordinary char* arguments alike, since the safe direction of conversion runs toward const — so this fix routinely deletes caller-side workarounds as a side effect.
Two checks keep this fix honest. First, follow the text all the way through the call chain before changing a signature: a parameter can be made const only if the function body and everything it forwards the pointer to also refrain from writing, and a single downstream char* requirement — a call into a writing function, a return into a writable context — means the const cannot stop there; it must either propagate further or the design genuinely has a writable stage, which belongs to the later fixes. Second, expect the change to surface follow-on errors elsewhere, and read them as information rather than backsliding: each new error marks a place that was silently relying on the writability the old signature advertised. Work through them with the same question — does anything here write? — and most resolve as more const declarations. The ones that do not are the genuine writers, and they are exactly the sites the next two fixes exist for.
A special case of this fix deserves its own sentence: your own string literals used as defaults, labels, format strings, and lookup keys. These are read-only by intent in nearly all code, and any char* holding one is this error waiting for a stricter build to notice it. Declaring such variables const char* at the point of definition is the whole repair.
Fix 2: copy into a local array when the callee really writes
Some functions really do write. A routine that uppercases text in place, a parser that inserts terminators into the buffer it scans, a C API that edits the string it is given — these need writable characters, and no declaration change can substitute for supplying some. When the text is known at the call site and only needs to live for the duration of the call, the supplying move is a local array initialized from the literal:
#include <cctype>
#include <cstring>
#include <iostream>
void shout_in_place(char* text) {
for (std::size_t i = 0; text[i] != '\0'; ++i) {
text[i] = static_cast<char>(std::toupper(static_cast<unsigned char>(text[i])));
}
}
int main() {
char buf[] = "hello";
shout_in_place(buf);
std::cout << buf << '\n';
std::cout << sizeof(buf) << '\n';
return 0;
}
$ g++ -std=c++17 -g -Wall -Wextra -o fixed_array_copy fixed_array_copy.cpp
$ ./fixed_array_copy
HELLO
6
The output shows both halves of the claim. HELLO proves the callee's writes landed and were visible afterward — real modification of real storage, not a cast's pretense of it. The 6 is sizeof(buf): five letters plus the terminating null, the size of the array the declaration created. That number is the signature of the copy. buf is not a pointer to the literal; it is an array object of six writable char elements, initialized by copying the literal's contents under the character-array initialization rule, and it decays to a char* pointing at its own first element when passed to shout_in_place. The literal itself is never written, never cast, and never involved after the copy is made.
Choose this fix when three conditions hold together. The text is short and its size is known at compile time, or at least bounded small enough for a stack array whose size you state explicitly. The writable copy only needs to live within the current scope — the callee finishes with it during the call, or the result is consumed before the function returns. And a copy is semantically acceptable: the callee's edits are meant for this call's private text, not for some shared original — which, if the original was a literal or a const variable, they could never legitimately have reached anyway. When any condition fails — runtime-sized text, text that must outlive the scope, edits that must land in storage owned elsewhere — the array is the wrong tool and the next fix, owned string storage, is the right one.
Two mistakes recur around this fix and are worth naming. The first is declaring the array and then also keeping a pointer of the wrong kind into the literal for the actual call — the copy only helps if the callee receives buf, the copy, and the clean compile of the program above comes from exactly that hand-off. The second is sizing a hand-declared array too small for the text plus its terminator: char buf[] with an initializer cannot be undersized, because the compiler counts the literal, but an explicit size is a claim you must keep true yourself, terminator included. Prefer the deduced form wherever the initializer is present.
Fix 3: own the text in std::string and use data() when it must stay mutable
When writable text must be owned, resized, returned, stored, or simply live longer than one call, the supplying move is a std::string. The string owns a genuine, mutable character array, and since C++17 its non-const data() returns a char* pointing into that array — a real writable pointer, obtained without any cast:
#include <cctype>
#include <iostream>
#include <string>
void shout_in_place(char* text) {
for (std::size_t i = 0; text[i] != '\0'; ++i) {
text[i] = static_cast<char>(std::toupper(static_cast<unsigned char>(text[i])));
}
}
int main() {
std::string s = "hello";
char* p = s.data();
shout_in_place(p);
std::cout << s << '\n';
std::cout << s.size() << '\n';
const std::string t = "world";
const char* q = t.c_str();
std::cout << q << '\n';
return 0;
}
$ g++ -std=c++17 -g -Wall -Wextra -o fixed_string_data fixed_string_data.cpp
$ ./fixed_string_data
HELLO
5
world
The first two lines are the fix working: the in-place routine wrote through the pointer data() returned, and the string itself now reads HELLO with its size unchanged at 5 — the writes went to the string's own storage, through a pointer the string's own interface issued for exactly that purpose. The third line is the same object family used in the read-only direction: a const string's c_str(), held in a const char*, printing without ceremony. One type supplies both directions, each through the accessor whose const matches the intent.
The details of data() that decide whether this fix is safe in your code are these. There are two overloads: the const overload returns const char*, and the non-const overload, present since C++17, returns char*. Calling data() on a non-const string selects the writable one; calling it on a const string selects the read-only one, which is the failure shown at the end of the c_str() section. Since C++11, data() and c_str() perform the same function on the same storage, and the array is null-terminated: the pointer range runs through the character at position size(), which is the null character. What may be written through the non-const pointer is the string's contents — the characters at positions below size(). The terminating null at position size() is not ordinary content: modifying that stored terminator to any value other than the null character is undefined behavior, so a callee that needs to change the text's length must not be handed this pointer and told to edit freely; length changes belong to the string's own member functions, after which a fresh pointer can be taken. And like every pointer into a string, the one from data() is invalidated by the operations that can reallocate the storage — passing the string by non-const reference to a standard library function, or calling non-const member functions outside a small excluded set that includes operator[], at(), front(), back(), and the iterator accessors. Take the pointer, use it for the call, and take it again after any operation on the string that could have moved the storage.
For element access without a raw pointer at all, the non-const operator[] of std::string returns a char& to the character at the given position, so s[0] = 'H'; modifies a non-const string directly, with the address of that reference being exactly data() + 0 — the two routes reach the same storage, and code that only needs character-level edits can stay with the operator and never name a pointer. The pointer form earns its place at API boundaries: where a function takes char*, s.data() is the one-expression bridge from owned C++ storage to a writable C-style call, valid from C++17 onward. Before C++17 there was no such overload — data() returned only const char* — which is why older code is full of the idiom of passing the address of the first element, and why a project still pinned to C++14 cannot use this fix as written and should take the array copy or restructure instead.
Fix 4: const_cast, for one narrow legacy case only
Every fix so far changed a declaration or supplied genuinely writable storage. The remaining tool changes neither: const_cast converts a const char* to a char* by casting away the constness, leaving the pointer aimed at the very same characters. Only const_cast may be used to cast away constness, and its existence is not a general license — it is a precision instrument for one situation, and using it outside that situation converts a compile-time error into undefined behavior at runtime, which is a trade in the wrong direction.
The one situation has two halves, and both must hold. First, the underlying object is genuinely mutable: the characters were not created const — they live in ordinary writable storage that merely reached this point through a const view, for example a non-const array that was passed through a const char* parameter or stored behind a const char* variable on its way to the call. Second, the receiving API does not actually write through the pointer: its char* parameter is a historical artifact — an old C interface, written before const-correct signatures were customary — and its contract, documentation, or source establishes that it only reads. When both halves hold, the cast tells the compiler a true fact it cannot see across the interface boundary: this storage is writable in reality, and no write will occur anyway. Here is that case, complete:
#include <cstring>
#include <iostream>
// Legacy-style API: takes char* for historical reasons but only reads.
void legacy_length(char* text, std::size_t* out) {
*out = std::strlen(text);
}
int main() {
char storage[] = "hello";
const char* view = storage;
std::size_t n = 0;
legacy_length(const_cast<char*>(view), &n);
std::cout << n << '\n';
std::cout << storage << '\n';
return 0;
}
$ g++ -std=c++17 -g -Wall -Wextra -o fixed_const_cast_legacy fixed_const_cast_legacy.cpp
$ ./fixed_const_cast_legacy
5
hello
Trace the ownership, because the trace is the justification. storage is a plain array of writable characters, created non-const in main. view is a const view of that same array — taking it was the safe-direction conversion, discarding write access for the journey. At the call, the legacy signature demands the access back. The const_cast restores a pointer to storage that was never const in itself, and legacy_length honors the second half by only measuring the text: the outputs are the length, 5, and the storage afterward, unchanged at hello. Remove either half and the same line of code stops being defensible. If storage had been created const, or if legacy_length wrote a terminator into the middle of the text, the cast would be the mechanism of a bug rather than the bridge over an old signature.
Now the boundary, demonstrated rather than asserted. Casting away const compiles even when it should not be used — the cast is a statement by the programmer, and the compiler accepts the statement without auditing the storage behind it. This program applies const_cast to a pointer at a literal and merely reads through the result:
#include <iostream>
int main() {
const char* lit = "hello";
char* p = const_cast<char*>(lit);
std::cout << p << '\n';
return 0;
}
$ g++ -std=c++17 -g -Wall -Wextra -o cast_literal_compiles cast_literal_compiles.cpp
$ ./cast_literal_compiles
hello
It compiles without a diagnostic under the guide's ordinary flags, and it runs and prints the text. Forming the pointer, and even reading through it, is not where the undefined behavior lives. The behavior is undefined at the moment of modification: attempting to modify a string literal object is undefined, and modifying a const object through a non-const access path is undefined behavior in general. The cast did not make the literal writable; it only made the compiler stop saying so. The final program takes that one step — a single write through the cast pointer:
#include <iostream>
int main() {
const char* lit = "hello";
char* p = const_cast<char*>(lit);
p[0] = 'H';
std::cout << p << '\n';
return 0;
}
This program also compiles without a diagnostic. Run on the machine used for this guide, it printed nothing and terminated with a segmentation fault — exit status 139, the shell reporting Segmentation fault — on each of two runs: the write was aimed at the literal's storage, which the program could not modify. Report that result with its exact scope, though, because undefined behavior guarantees nothing, including the crash: on another machine, another build, or another optimization level, the same program might print Hello, print hello, corrupt something unrelated, or appear to work for years. The crash is evidence of how unforgiving this storage is on one real system, not a specification of what the program does. The only portable statement about writing through a cast taken from a literal is the language's: it is undefined behavior, and const_cast is never the fix for a literal, a const variable over const storage, or a c_str() result. Those cases belong to fixes 1 through 3.
The working rule for const_cast on text is therefore short enough to apply at the keyboard. Name the object the pointer ultimately points to, in its original declaration. If that declaration is const, or the object is a literal, or the storage belongs to a std::string you reached through c_str() — stop; use a copy, a string, or a const signature. If that declaration is an ordinary writable object, and the receiving function is established not to write, the cast is the documented, narrow bridge — and it should sit at the call site, visible, rather than being hidden inside a helper that hands out writable pointers to const text as a general service.
The trap: -fpermissive and other ways to silence the error
[-fpermissive] inside the title error, and sooner or later someone on the project suggests using it. The flag downgrades this error — and a family of others — from an error to a warning, letting the build proceed. Here is exactly what accepting that offer does to the argument-failure program from earlier, built without -pedantic-errors:$ g++ -std=c++17 -fpermissive -g -Wall -Wextra -o fail_const_arg_perm fail_const_arg.cpp
fail_const_arg.cpp: In function 'int main()':
fail_const_arg.cpp:9:17: warning: invalid conversion from 'const char*' to 'char*' [-fpermissive]
9 | print_label(name);
| ^~~~
| |
| const char*
fail_const_arg.cpp:3:24: note: initializing argument 1 of 'void print_label(char*)'
3 | void print_label(char* text) {
| ~~~~~~^~~~
fail_const_arg.cpp:10:17: warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]
10 | print_label("ready");
| ^~~~~~~
$ ./fail_const_arg_perm
status
ready
The program built, ran, and printed both labels — because print_label happens not to write, so the manufactured permission was never exercised. That happy outcome is precisely the trap: the flag did not establish that the conversion was safe; it suppressed the one check that was asking. Every call site the flag waves through is a place where read-only text now flows into a writable signature with no record of whether the receiving function writes, and the day one of those functions is edited to write — by someone who trusts its signature, as they should — the failure arrives as corrupted literals or a crash in code that compiled cleanly. The same objection covers the flag's manual equivalents: a C-style cast, which can also cast away constness without naming the operation, and a reinterpret_cast-based detour. A C-style cast on this conversion compiles for the same reason const_cast does and hides the intent from anyone searching the code for casts later; const_cast, used inside its narrow case, at least announces itself. Silencing mechanisms all share the defect that they answer the compiler instead of answering its question. The question — does anything write to this text? — has a correct answer in every real program, and fixes 1 through 4 are how each possible answer is written down.
The fixes, ranked
Add const, when nothing writes. Change the variable, parameter, or return type to const char*. This is the correct fix for the great majority of occurrences: the char* was habit, not need. It costs nothing at runtime, widens what the function accepts, and repairs every read-only call site at once when applied to a shared signature.
Copy into a local array, when a callee writes and the text is short-lived. char buf[] = "..."; creates owned, writable storage holding a copy of the literal, sized by the compiler, terminator included. Pass buf, never the literal. Reach for this when the writable text is needed only within the current scope.
Own the text in std::string and pass data(), when writable text must live. A non-const string's data() — C++17 and later — returns a genuine char* into storage the string owns, writable across its contents. Take the pointer at the call, respect its invalidation rules, and leave length changes to the string's member functions. On a const string, or before C++17, this route is closed; copy instead.
Use const_cast only across a legacy signature, over genuinely mutable storage, to a function established not to write. Both halves are required, every time: the original object was declared non-const, and no write occurs through the cast pointer. Never on a literal, never on storage created const, never on a c_str() result, and never as a way to make the error message stop.
Never downgrade the error. No -fpermissive, no C-style cast to the same effect, no warning suppression aimed at this diagnostic. Each converts a compile-time question with a known answer into a runtime risk with an unknown one.
Which fix for which error
error: invalid conversion from 'const char*' to 'char*'on a variable initialization: the variable claims writability its initializer does not offer. Declare itconst char*if the function only reads through it; if a later call needs writable text, supply a copy or a string at that call instead.- The same error at a function call, with the note
initializing argument 1 of 'void ...(char*)': the requirement is created by the parameter. If the function is yours and never writes, change the parameter toconst char*and every read-only caller is repaired. If the signature is external, supply writable storage — array copy for a short call,std::stringplusdata()for owned text. warning: ISO C++ forbids converting a string constant to 'char*'on a literal assignment or argument: the same problem in its historical wording, and only a warning under GCC's default flags. Treat it with the same seriousness as the error — it becomes one under-pedantic-errors— and fix it by the same choice: const declaration, array copy, or owned string.- The title error on
s.c_str(): the accessor is read-only by design. If only reading follows, hold the result in aconst char*. If writing into the string's own storage is genuinely required and the string is non-const, uses.data()under C++17 or later — and if the string is const,data()fails identically, so copy the text into non-const storage first. - A compile that succeeds only because of a cast at the call site: audit the cast before trusting the build. If the pointed-to object was not declared as ordinary writable storage, or the callee's no-write property is assumed rather than established, the program is undefined where it writes — replace the cast with one of the supplying fixes.
Checklist
- Answer the compiler's question first, in words: does any code write through this pointer, anywhere along its whole path? The answer, not the error message, selects the fix.
- Read which side created the requirement: the underlined expression has the const type; the note, when present, shows the declaration demanding
char*. Edit the side that is wrong — usually the declaration. - Default to
const char*for labels, defaults, format strings, literals, and every parameter whose function only reads; propagate const through forwarding parameters and return types until it reaches a genuine writer. - When a writer is genuine and the text is local and known, copy:
char buf[] = "...";— and confirm the callee receives the array, sized with its terminator. - When writable text must be owned or outlive the call, hold it in a non-const
std::stringand passdata()(C++17 or later); retake the pointer after any operation that could reallocate, and never rewrite the terminating null at positionsize()to a non-null value. - Before any
const_cast, name the original declaration of the storage. Non-const original plus a callee established not to write: the cast is the narrow legacy bridge. Anything else: stop, and use a supplying fix. - Search the build log for both wordings — the
invalid conversionerror and theconverting a string constantwarning — because one codebase routinely carries both, and the warning form is the one that survives inattention. - Keep
-fpermissiveand cast-based silencing out of the build: a conversion that only compiles under them is a defect the compiler already diagnosed.
Related guides on this site
- C++ Pointers and References — the underlying model this error tests: what a pointer holds, what the pointee's qualification means, and how the safe direction of conversion runs.
- Fix C++ "request for member in pointer type" — the sibling pointer error, where the operand's kind and the access operator disagree, separated into its pointer-type and non-class forms.
- Fix C++ "'cout' was not declared in this scope" — the sibling first-build error in the same minimal programs: a name-lookup failure on the stream object, separated into its missing-header and missing-qualification causes.
Sources
- cppreference, String literal — for the ordinary string literal having type
const char[N], for the literal object having static storage duration and modification of it being undefined, for string literals not being convertible or assignable to non-constchar*since C++11 with the pre-C++11 conversion deprecated, and for character arrays initialized from a literal containing a copy of the literal's characters. - cppreference, const_cast conversion — for only
const_castbeing able to cast away constness, for the cast result pointing to the same object, and for modifying a const object through a non-const access path resulting in undefined behavior. - cppreference, std::basic_string::data — for the const overload returning
const CharT*and the non-const overload returningCharT*since C++17, for the array being null-terminated anddata()andc_str()performing the same function since C++11, for the invalidation rules, and for modifying the stored terminator atdata() + size()to a non-null value being undefined behavior. - cppreference, std::basic_string::c_str — for
c_str()returningconst CharT*in all standards, for writing to the character array accessed throughc_str()being undefined behavior, and for the invalidation rules for the returned pointer. - cppreference, std::basic_string element access — for the non-const overload returning a reference to the character at the given position, writable on a non-const string, and for that reference's address being
data() + pos.
Keep Exploring
Seven tips and seven puzzles so far, each one a short runnable example with the fix explained.
Paste an AddressSanitizer, UBSan, or ThreadSanitizer report and get the bug, the file and line, and the fix \u2014 in plain language.
C++20 and C++23 features, migration paths, and measured trade-offs.
The full C++ hub \u2014 language basics, the standard library, coroutines, and measured comparisons.
Paste a [Service] section and get a plain-language verdict on every sandboxing setting it finds.