At work I found this code in my codebase, where chars are casted twice:
constexpr unsigned int foo(char ch0, char ch1, char ch2, char ch3)
{
return ((unsigned int)(unsigned char)(ch0)
| ((unsigned int)(unsigned char)(ch1) << 8)
| ((unsigned int)(unsigned char)(ch2) << 16)
| ((unsigned int)(unsigned char)(ch3) << 24))
;
}
Wouldn't one cast to unsigned int
be sufficient?
And in that case better make it a static_cast<unsigned_int>
?
constexpr
. The rest is C style casts.char
is a signed type on many platforms. Consider what happens whench0
is-1
.static_cast
is a better choice here because if you do screw up, the compiler can catch the mistake.