Search code examples
c++castingtype-conversionexplicit-conversion

In C++, can we use { } for C-Style casting?


While I have been reading about datatype conversion, I saw this example:

void intval()
{
    for (char c; cin >> c; )
    cout << "the value of '" << c << "' is " << int{c} << '\n';
}

I know that we can cast using:

  1. int(c)
  2. (int) c
  3. static_cast<int>(c)

My questions:

Q1: Is int{c} another way of casting data types?

Q2: After some research on the net, I know that C++ casting is different and it have the compiler check the casting possibility at the compile time, but what are the differences between 1 and 2? And how int{c} is different if it is just another casting way?

Q3: Are there any other ways to explicitly convert/cast?


Solution

  • Is int{c} another way of casting data types?

    Yes. T{value} creates a temporary of type T that is direct-list-initialized with the specified braced-init-list. This cast does have an advantage over T(value) in that T{value} can be used to create a temporary array. That would be done like

    int main() {
        using int_array = int[5];
        for( auto e : int_array{1,2,3,4,5})
            std::cout << e;
    }
    

    It also comes with the caveat that a narrowing conversion is a error

    int main() {
        int(10000000000ll);  // warning only, still compiles
        int{10000000000ll};  // hard error mandated by the standard
    }
    

    After some research on the net, I know that C++ casting is different and it have the compiler check the casting possibility at the compile time, but what are the differences between 1 and 2?

    The big difference between T(value) and (T)value is that in T(value), T must be a single word. For example

    int main() {
        unsigned int(10000000); // error
        (unsigned int)10000000; // compiles
    }
    

    Q3: Are there any other ways to explicitly convert/cast?

    Well in C++ they want you to use the C++ casts which are static_cast, reinterpret_cast, dynamic_cast, and const_cast. Those are preferred over c style cast as a c style cast will do all of those where the C++ versions have certain limitations and come with certain guarantees.