Open In App

Why is Conversion From String Constant to ‘char*’ Valid in C but Invalid in C++?

Last Updated : 02 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In both C and C++, strings are sequences of characters enclosed in double-quotes. In this article, we will learn why is the conversion from string constant to ‘char*’ valid in C but invalid in C++.

Conversion From String Constant to char*

In C, it’s permissible to assign a string constant to a ‘char*’ variable and the reason behind it is historical. When C was developed, the ‘const’ keyword didn’t exist, so string constants were just ‘char[]’. Therefore, for backward compatibility, C allows assigning a string constant to a ‘char*’.

For example, the following code is valid in C:

char *str = "Hello, World!";

On the other hand, in C++, assigning a string constant to a ‘char*’ is not allowed and will result in a compilation error because C++ is stricter with type safety and string constants are of type ‘const char[]’, and cannot be assigned to pointer to a non-const char.

For example, the same code will give an error in C++:

char *str = "Hello, world!";   // error: ISO C++ forbids converting a string constant to 'char*'

To resolve this error in the case of C++, we can use the const keyword.

const char *str = "Hello, World!";

C++ Program to Resolve the Issue of Conversion of a String Constant to char *

The below program demonstrate how we can convert from string constant to char* in C++.

C++
// C++ program to demonstrate how we can convert from string
// constant to char*
#include <iostream>
using namespace std;

int main()
{
    // Conversion from string constant to const char* is
    // valid in C++
    const char* str = "Hello, World!";
    cout << str << endl;

    // We can also Use string in place of char* in C++
    string str2 = "Hello, Geeks!";
    cout << "String: " << str2 << endl;
    return 0;
}

Output
Hello, World!
String: Hello, Geeks!

Note: In general, it is best to avoid using pointers to char in C++. Instead, we should use the std::string class as it is a safe and efficient way to store and manipulate strings.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads