Convert char * to const char * in C ++
How to convert char * to const char * in C ++? Why program 1 works but program 2 can't?
Prog 1 (working):
char *s = "test string";
const char *tmp = s;
printMe(tmp);
void printMe(const char *&buf) {
printf("Given Str = %s", buf);
}
Prog 2 (not working)
char *s = "test string";
printMe((const char *)s); // typecasting not working
void printMe(const char *&buf) {
printf("Given Str = %s", buf);
}
Mistake:
x.cpp:10:15: warning: conversion from string literal to 'char *' is
deprecated [-Wc++11-compat-deprecated-writable-strings]
char *s = "test string";
^
x.cpp:12:5: error: no matching function for call to 'printMe'
printMe(s);
^~~~~~~
x.cpp:6:6: note: candidate function not viable: no known conversion
from 'char *' to 'const char *&' for 1st argument
void printMe(const char *&buf)
^
1 warning and 1 error generated.
source to share
printMe
accepts an lvalue reference to a mutable pointer to const char.
Your first example tmp
is an lvalue of type mutable pointer to const char, so a reference can be bound to it without issue.
The second example (const char*)s
creates a temporary object const char*
. Lvalue references to mutable objects cannot bind to temporary objects, so you get an error. If you change printMe
to take const char* const&
, then the call will be made with or without an explicit lit.
void printMe(const char * const& buf) {
printf("Given Str = %s", buf);
}
int main() {
char s[] = "test string";
printMe(s);
}
Of course, if you don't want to modify the object (pointer) passed to printMe
, then there is no reason to use a reference at all. Just try const char*
:
void printMe(const char * buf) {
printf("Given Str = %s", buf);
}
int main() {
char s[] = "test string";
printMe(s);
}
After all, this is the same reason:
void doSomething(const std::string& s) {}
int main() {
doSomething("asdf");
}
works as long as this:
void doSomething(std::string& s) {}
int main() {
doSomething("asdf");
}
not. A temporary object is created and a reference to a non-const object cannot bind to the temporary.
source to share