1

I am new to explicit casts in C++. I thought that static_cast was way more restrictive than reinterpret_cast. However, I have a function where static_cast gives me the desired result and reinterpret_cast tells me that my conversion is invalid. Why is this happening?

void    from_int(int x)
{
    if (x < 32 || x > 126)
        std::cout << "char: Non displayable" << std::endl;
    std::cout << "char: '" << reinterpret_cast<char>(x) << "'" << std::endl;
    std::cout << "int: " << x << std::endl;
    std::cout << "float: " << x << ".0f" << std::endl;
    std::cout << "double: " << x << ".0" << std::endl;
}
kubo
  • 221
  • 1
  • 8
  • I mis-interpreted reinterpret_cast the same as a C-style cast, but it is not. See https://stackoverflow.com/questions/60602983/why-does-reinterpret-castintlparam-generate-c2440-error – franji1 Sep 15 '21 at 14:06

1 Answers1

4

static_cast is more restrictive than reinterpret_cast when performing a cast from one pointer type to another. With reinterpret_cast, such a cast will always compile (assuming the cast is from object pointer to object pointer or function pointer to function pointer).

reinterpret_cast is narrowly tailored to such pointer casts, analogous reference casts, and casts between pointer and integer types. What you want to do here is perform an implicit conversion. In such cases, as well as when you want to perform the reverse of an implicit conversion, static_cast is usually the correct choice. Some programmers use a user-defined "implicit_cast" template which is even weaker than static_cast, but safer (it only performs implicit conversions).

Brian Bi
  • 111,498
  • 10
  • 176
  • 312