Either of below methods gives me the same value when I use it on a char type variable. So what are the differences between them?
(int)c
int{c}
static_cast<int>(c)
Either of below methods gives me the same value when I use it on a char type variable. So what are the differences between them?
(int)c
int{c}
static_cast<int>(c)
For starters using eth functional notation of casting requires s simple type specifier.
That is you may not for example write
unsigned int( c )
The functional notation of a casting creates a temporary object.
While using the explicit type conversion you may create for example an lvalue reference.
Here is a demonstrative program.
#include <iostream>
int main()
{
char c = 'A';
++( char &)c;
std::cout << "c = " << c << '\n';
}
From the C++ Standard (5.2.3 Explicit type conversion (functional notation)
3 Similarly, a simple-type-specifier or typename-specifier followed by a braced-init-list creates a temporary object of the specified type direct-list-initialized (8.5.4) with the specified braced-init-list, and its value is that temporary object as a prvalue.
As for static_cast
then accoding to the C++ Standard (5.2.9 Static cast)
1 The result of the expression static_cast(v) is the result of converting the expression v to type T. If T is an lvalue reference type or an rvalue reference to function type, the result is an lvalue; if T is an rvalue reference to object type, the result is an xvalue; otherwise, the result is a prvalue. The static_cast operator shall not cast away constness