Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast from float to double

Can someone please explain me why this code doesn‘t compile:

boolean r = (boolean) 0;

Why does this one compile?

double z = (float) 2.0_0+0___2;

I don‘t understand the Alphabet in which the numbers after float are written.

like image 626
Katja Avatar asked Jan 02 '23 19:01

Katja


1 Answers

The first one doesn't compile because you simply can't cast a number to a boolean. A boolean is true or false.

The second one just uses underscores, which can be used to separate numbers like 2_000_000 for improved readability. In this case they're used to decrease readability, as is the cast to float (a double cast to float and assigned to double doesn't do anything in this particular case).

The latter case seems to be designed for confusion, as there are several pitfalls. If we remove the unnecessary underscores we get 2.00+02 which adds a literal double with an octal 02. This is still basically just 2+2, but if the octal value were 0___10 you'd get a result of z = 10. Then you have the cast to float which could affect the final result, as 64 bits are forced to 32 bits and then back to 64 bits. This could make the end result less precise than without the cast.

like image 58
Kayaman Avatar answered Jan 11 '23 10:01

Kayaman