![]() |
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.
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++.
Output Hello, World! String: Hello, Geeks!
|
Reffered: https://www.geeksforgeeks.org
C++ |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 15 |