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.