Is there any different?

i was wondering the casting of below statement has any difference or not?
1
2
double d = 3;
int i = static_cast<int>(d);


and

1
2
double d = 3;
int i = (int)d;


if they have no difference, which one is recommend to use as a beginner?
In this case, the result it the same.

The old style cast was replaced by four distinct kinds of cast in C++ is because you can never be sure what the old style cast is doing. The four distinct kinds of cast in C++ allow you to say what kind of cast you want and allows the compiler to check that the cast is allowed.
it mean that both way are different? but how come it give same result?
The former specifies to the compiler what kind of cast you wish to happen, and the latter you let the compiler choose. I believe
ResidentBiscuit has said it better that I could.

The catch of course is that using the latter syntax, the compiler will do whatever it takes to make the cast happen if it is at all possible. However; in C++ you usually don't want this. Hence the new cast syntax.
From what I've learned/been told, you never really want the compiler to do anything implicitly. If you can make it explicit, do it. I'm sure this is debatable, but it's what I do
it mean that both way are different? but how come it give same result?


Different operations can have the same result.

Here's an example.

int x = 3+4;
or
int x = 7;

OMG! Both have same result! :)
it mean that both way are different? but how come it give same result?


By definition, the C-style cast such as (int)d; tells the C++ compiler to consider, in this order:

a const_cast
a static_cast
a static_cast followed by a const_cast,
a reinterpret_cast
a reinterpret_cast followed by a const_cast

In your case, const_cast<int>(d) is invalid C++, so the compiler does not attempt that. Then it looks at static_cast<int>(d). That is valid C++, so the compiler produces the machine code for static_cast<int>(d), which is the same as if you'd have used static_cast<int>(d) directly.
Topic archived. No new replies allowed.