C++ Casting – Converting char* to const char* and Managing Pointers

c++castingconstantspointersreference

How to convert char* to const char* in C++? Why program 1 is working 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);
}

The error I receive:

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.

Thanks.

Best Answer

printMe takes an lvalue reference to a mutable pointer to const char.

In your first example, tmp is an lvalue of type mutable pointer to const char, so a reference can be bound to it without issue.
In your second example, (const char*)s creates a temporary const char* object. Lvalue references to mutable objects can't bind to temporaries, so you get an error. If you change printMe to take a const char* const& then the call will succeed with or without the explicit cast.

void printMe(const char * const& buf) {
    printf("Given Str = %s", buf);
}

int main() {
    char s[] = "test string";
    printMe(s);
}

Live on Coliru

Of course, if you don't want to alter the object (the pointer) passed into printMe, then there's no reason to use a reference at all. Just make it take a const char*:

void printMe(const char * buf) {
    printf("Given Str = %s", buf);
}

int main() {
    char s[] = "test string";
    printMe(s);
}

Live on Coliru

In the end, this is the same reason something like this:

void doSomething(const std::string& s) {}
int main() {
    doSomething("asdf");
}

works while this:

void doSomething(std::string& s) {}
int main() {
    doSomething("asdf");
}

does not. A temporary object is created, and the reference to non-const object can't bind to the temporary.

Related Question