C++ style cast from unsigned char * to const char *
C++ConstantsCastingC++ Problem Overview
I have:
unsigned char *foo();
std::string str;
str.append(static_cast<const char*>(foo()));
The error: invalid static_cast from type ‘unsigned char*’ to type ‘const char*’
What's the correct way to cast here in C++ style?
C++ Solutions
Solution 1 - C++
char *
and const unsigned char *
are considered unrelated types. So you want to use reinterpret_cast
.
But if you were going from const unsigned char*
to a non const
type you'd need to use const_cast
first. reinterpret_cast
cannot cast away a const
or volatile
qualification.
Solution 2 - C++
Try reinterpret_cast
unsigned char *foo();
std::string str;
str.append(reinterpret_cast<const char*>(foo()));
Solution 3 - C++
reinterpret_cast
Solution 4 - C++
unsigned char* is basically a byte array and should be used to represent raw data rather than a string generally. A unicode string would be represented as wchar_t*
According to the C++ standard a reinterpret_cast between unsigned char* and char* is safe as they are the same size and have the same construction and constraints. I try to avoid reintrepret_cast even more so than const_cast in general.
If static cast fails with what you are doing you may want to reconsider your design because frankly if you are using C++ you may want to take advantage of what the "plus plus" part offers and use string classes and STL (aka std::basic_string
Solution 5 - C++
You would need to use a reinterpret_cast<>
as the two types you are casting between are unrelated to each other.
Solution 6 - C++
Too many comments to make to different answers, so I'll leave another answer here.
You can and should use reinterpret_cast<>
, in your case
str.append(reinterpret_cast<const char*>(foo()));
because, while these two are different types, the 2014 standard, chapter 3.9.1 Fundamental types [basic.fundamental]
says there is a relationship between them:
> Plain char
, signed char
and unsigned char
are three distinct types, collectively called narrow character types. A char
, a signed char
, and an unsigned char
occupy the same amount of storage and have the same alignment requirements (3.11); that is, they have the same object representation.
(selection is mine)
Here's an available link: https://en.cppreference.com/w/cpp/language/types#Character_types
Using wchar_t
for Unicode/multibyte strings is outdated: https://stackoverflow.com/questions/17871880/should-i-use-wchar-t-when-using-utf-8
Solution 7 - C++
> Hope it help. :) >
const unsigned attribName = getname();
const unsigned attribVal = getvalue();
const char *attrName=NULL, *attrVal=NULL;
attrName = (const char*) attribName;
attrVal = (const char*) attribVal;