Question

I try to understand when casting causes data losing and how it works. so for the following examples i try to understand if there is data loss and if yes why: (i - int(4),f - float(4),d-double(8))

i == (int)(float) i; // sizeof(int)==sizeof(float) <- no loss
i == (int)(double) i; // sizeof(int)!=sizeof(double) <- possible loss
f == (float)(double) f;// sizeof(double)!=sizeof(float) <- possible loss
d == (float) d;// sizeof(double)!=sizeof(float) <- possible loss

Is it sufficient to base the answer only on type sizes?(+ round )

Was it helpful?

Solution

Assuming 32 bit ints and normal 4 and 8 byte IEEE-754 floats/doubles it would be:

i == (int)(float) i;     // possible loss (32 -> 23 -> 32 bits)
i == (int)(double) i;    // no loss (32 -> 52 -> 32 bits)
f == (float)(double) f;  // no loss (23 -> 52 -> 23 bits)
d == (float) d;          // possible loss (52 -> 23 -> 52 bits)

Note that int has 32 bits of precision, float has 23 bits, double has 52.

OTHER TIPS

The memory allocated to store variable of a type is not the only fact for you to consider loss of data. Generally, way to roundoff and how CPU processes numeric data in case of overflow would be other aspects you might want to look into.

Because the sizeof reports the same size in memory does not mean there is data loss.

Consider 0.5.

Can store that in a float but cannot store it in an integer.

Therefore data loss.

I.e. I want 0.5 of that cake. Cannot represent that as an integer. Either get nothing or lots of cakes. Yum

Why integer? because you may need only integer numbers for example an ID_num

Why float? because you may need to work on real numbers example % calculations

Why double? when you have real numbers that cannot fit into float size

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top