Casting

Started by
9 comments, last by simius 13 years, 9 months ago
Alright be truthful, and don't tell me what should be done. Tell me what you do.
What I am referring to is what type of casting do you normally in C++. For example:
//Different ways to cast   float x = 123.321f;[1]int a = (int)x;[2]int b = int(x);[3]int c = x; //implicit[4]int d = static_cast<int>(x);[5]int e = boost::lexical_cast<int>(x);	/* EDIT: Thanks SiCrane */[6]int e = castTo<float>(x); //own implementation


If I missed some then just add em. But besides recommending [5] or [4] instead
of the other ones, which type of cast do you normally do in your
project. This post is just for fun and for you to CONFESS YOUR SINS.

[Edited by - Concentrate on August 1, 2010 5:41:03 PM]
Edge cases will show your design flaws in your code!
Visit my site
Visit my FaceBook
Visit my github
Advertisement
I use [3] if possible. If the cast needs to be explicit I use [1].
I always do [4] (static/dynamic/reinterpret_cast<>, which ever applies). There's no good reason not to, helps remove warnings, and maintains the original intent for anyone else who looks at the code later.
I use [1]. I also use myobj* obj = new myobj[initval] and std::cout <<. I am a bad bad man.
"It's like naming him Asskicker Monstertrucktits O'Ninja" -Khaiy

I don't use C++, but when i cast in Java or C# I use [1].
"Anyone who has never made a mistake has never tried anything new." - Albert Einstein
Being explicit is best - I would use #4. #3 Should trigger a warning, if not see if you can increase your warning level.
I assume by number five you actually meant boost::lexical_cast<int>(x)? Given that it'll throw an exception if that's the case, it has some very different behavior than the other options you listed.
I prefer number 2 whenever I don't feel like changing an integer that I need in a floating point calculation(which is pointless because they're the same size right? and who ever honestly runs into the maxes frequently...)
I use #4 most times. If I am lazy, I use #1.
-----The scheduled downtime is omitted cause of technical problems.
Perhaps for [5] you meant boost::numeric_cast, which has error checking that could be useful sometimes.

I thought lexical cast was good for converting things to and from strings.

This topic is closed to new replies.

Advertisement