These two lines taken from a recent patch (the anonymous author will hopefully forgive me posting them here) show that C++ casts are not better in any way:
- if(abs(compilerIdx)>=CompilerFactory::Compilers.GetCount())
+ if(static_cast<unsigned>(compilerIdx)>=CompilerFactory::Compilers.GetCount())
This patch's purpose is to remove "comparing signed vs. unsigned " compiler warning because
abs declares as
int abs(int).
The introduced C++ cast will remove the warning by making the compiler treat the number as
unsigned, however, it did not only fool the compiler, but also the programmer!
static_cast<unsigned> looks so good and so innocent. Except that without
abs(), it is not unsigned at all, you only treat it as such. Thus, a value of
-1 now becomes
4294967295. By mere coincidence (because of the
>= comparison) the above code might still work, but it is clearly wrong.
And this is my whole point: C++ casts
are not better than C casts.
They are different, more explicit, but
not better.
Casts are a means to break the rules of the language and change the semantics of data, not more, not less. Using casts can likewise shoot your foot or blow away your whole leg, whether you use C or C++.