I am trying to eliminate all C-style casts in a codebase, due to cppcheck cstyleCast style warnings.
Is it always safe to change a C-style cast to a static_cast
?
By safe, I mean, is there a situation where the old C-style cast would work fine, but static_cast
would raise error or undefined behavior?
type1 a;
type2 b = (type2)a; // C style cast
type2 b = static_cast<type2>(a); // Is this always a valid replacement for above cast?
C-style cast is generally a combo of static_cast<>
or reinterpret_cast<>
with const_cast<>
. There might be compile-time errors from replacing it with just static_cast<>
.
I am not aware of any cases for runtime errors.
You could start with static_cast<>
, then add (or replace it with) const_cast<>
where compile-time errors arise. If after that you still have compile-time errors, reinterpret_cast<>
are required. But do not make the replacement blindly - some of these cases may be bugs. E.g., reinterpret_cast<>
may be required if a data type is forward declared but not defined, which leads to unspecified behavior (and will definitely cause problems if multiple inheritance is involved).
Finding these kinds of bugs is the reason why this exercise improves safety of the source code, and why a static code analyzer flags C-style casts.
C- style cast and static_cast
are not equivalent.
is there a situation where the old C-style cast would work fine, but static_cast would raise error or undefined behavior?
As an example:
int main() {
using FI = int(*)();
using FV = void(*)();
FI fi = nullptr;
FV fv = (FV)fi;
//FV fv2 = static_cast<FV>(fi);
}
If you uncomment the line that uses static_cast
, the code doesn't compile.
As a side note, in this case you should rather use reinterpret_cast
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With