I am working on a Qt5 project written in C++. Building the project gives an error:
C2440: \'=\': cannot convert from \'const char [9]\' to \'char*\'<
String literals are constant data in C++ (compilers tend to store them in read-only memory when possible).
In C++11 and later, you can no longer assign a string literal directly to a pointer-to-non-const-char (char*
) 1.
1: though some C++11 compilers may allow it as a non-standard extension for backwards compatibility, which may need to be enabled manually via compiler flag.
So, you need to declare port_name
as a pointer-to-const-char instead (const char *
or char const *
). But then you will have to cast it back to a non-const char*
when passing it to SerialPort()
:
const char *port_name = "\\\\.\\COM4";
SerialPort arduino(const_cast<char*>(port_name));
Or simply:
SerialPort arduino(const_cast<char*>("\\\\.\\COM4"));
The alternative is to declare port_name
as a non-const char[]
buffer, copy the string literal into it, and then pass it to SerialPort()
:
char port_name[] = "\\\\.\\COM4";
SerialPort arduino(port_name);
In C++, in contrast to C, string literals are const
. So any pointer to such a string literal must be const
, too:
const char* port_name = "\\\\.\\COM4"; // OK
// char* port_name = "\\\\.\\COM4"; // Not OK