In the "Programming: Principles and Practice Using C++", "Section 8.5.7 Argument checking and conversion" the following example is given as evidence on how to properly convert types, but never clearly explains why you would use int()
vs static_cast<int>()
to convert from a double
to an int
. However, I'm still unclear on the benefits of static_cast<int>()
vs int()
.
void ff(int x);
void gg(double y) {
ff(y); // how would you know if this makes sense?
int x=y; //how would you know if this makes sense?
}
void ggg(double x) {
int x1 = x; // truncate x
int x2 = int(x);
int x3 = static_cast<int>(x); // very explicit conversion (17.8)
ff(x1);
ff(x2);
ff(x3);
ff(x); // truncate x
ff(int(x));
ff(static_cast<int>(x)); // very explicit conversion (17.8)
}
I checked section 17.8, but still didn't find clarity on this topic. Can someone help? I'm looking for a solution that compares static_cast with function-style cast.
Explicit type conversion is permissive [expr.type.conv]:
On the other-hand if you use it only for fundamental types it should be fine. It should be never used in generic code:
If you look for a short and safe cast use the brace-style: