I think automatic (implicit) type conversation are bad and want to use explicit casts only. Is this a good style?
I think automatic (implicit) type conversation are bad and want to use explicit casts only. Is this a good style?
Not necessarily. Implicit casts are designed to make your life easier, and if you use explicit casts all of the time, your code can become verbose to the point of unreadability. On the other hand, some confusing situations can be made easier to read with an explicit cast.
For example, consider some code that calls sqrt() on an integer. Do you really need a cast here?
I usually don't put casts in place when up-casting is involved; for example, an int being promoted to a double. But I consider it good style to put a cast in place for the opposite scenario, and your compiler probably does too if you turn up its warning level.Code:double n = sqrt(9);
In the end it's your choice. Just be aware that using casts all of the time can quickly make code unreadable. sqrt(9) is readable enough as it is.
dwk
Seek and ye shall find. quaere et invenies.
"Simplicity does not precede complexity, but follows it." -- Alan Perlis
"Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
"The only real mistake is the one from which we learn nothing." -- John Powell
Other boards: DaniWeb, TPS
Unofficial Wiki FAQ: cpwiki.sf.net
My website: http://dwks.theprogrammingsite.com/
Projects: codeform, xuni, atlantis, nort, etc.
In that particular example, I would have replaced "9" with "9." to avoid the type conversion. On the other hand, if the argument is an integer i, that won't work, so the point holds. Although in C++, sqrt() is overloaded to take and return either float, double, or long double, so an explicit cast might eliminate confusion about which is being used. Do you know if it uses the double version if an integer argument is passed to it?
I also really wouldn't use a cast operator for up-casts in a class hierarchy. I think, in fact, that it would be a bad thing to do.
All the buzzt!
CornedBee
"There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
- Flon's Law