Mixing data types ok?

Ok so I read that you can mix data types, however I'm not sure if this is something that's used all the time, or if it's something that should be avoided if possible. Thanks!

-Xitan
Uh, and what exactly is that?
when you mix data types in calculations. for example when you divide a float value like 15.5 by an integer such as 5 C++ will attempt to automatically hanle the mixing of the two, its called promotion. when one data type of a variable is temporarily converted to match the data type of another variable so that a math operation can be performed using the mixed data type. (definition off of google somewhere)
I wouldn't worry about it. Just be sure you are promoted to the right type before doing the math.

Something like:

1
2
3
4
5
6
7
// 3 / 2 is 1.5 logically... but:

double foo = 3 / 2;  // gives you 1.0, not 1.5

// whereas:

double foo = 3.0 / 2.0; // gives you 1.5 


These types of situations are all you have to watch out for.
@ Disch
Hey thanks, helps allot. Just one of those things to keep in mind.
OHH, well that would have cleared it up. Yeah there's really nothing wrong with that. As long as you aren't making some messed up conversions (like char-int). Mixing around floating points with integers is perfectly fine.
char-int
?
So it's okay to convert between integers and floating points, but not between integers of different sizes?
Well it's just kind of strange to convert from char to int. If you have reason then it makes sense but I'd say this code is rather odd.
1
2
3
char first = 'a';
int second = 3;
int third = first + second

Inherently the types are identical but in terms of purpose they are decidedly not, which is why I dislike the idea. But really there's no mechanical issue with it.
So you wouldn't make an std::basic_string<unsigned>?
@helios quick question, std::, that's only needed if you don't declare using namespace std; correct?
Last edited on
std:: is the scope of most of the calls in C++ that use a namespace. You should *not* type an std if you've already put in a using directive.
You should *not* type an std if you've already put in a using directive.
It doesn't hurt.
Really? It doesn't cause errors?
Wow, I had no idea...
In general though there's no reason if you have a global using directive.
Last edited on
Topic archived. No new replies allowed.