Wouldn't it be a waste of space to always go for a double no matter the floating point? AFAIK float is using 4B or 32 bits, and a double taking up 8B or 64 bits. Why wouldn't compiler be able to tell if the float would be enough?
Asked
Active
Viewed 96 times
-6
-
7`0.5` is double, `0.5f` is float. – 273K Sep 20 '20 at 04:28
-
1Check out https://en.cppreference.com/w/cpp/language/floating_literal, specifically the part concerning the optional suffix on the floating point literal. – PaSTE Sep 20 '20 at 04:31
-
*"Why wouldn't compiler be able to tell if the float would be enough?"* -- this question is irrelevant, as the language designers decided to not give the compiler a chance. – JaMiT Sep 20 '20 at 04:43
-
It's only a waste of space if you know the range of all the values that **might** be assigned to `x` later on. – Pete Becker Sep 20 '20 at 14:33
-
I probably should have proposed a change in my previous comment. Rather than asking about a compiler's ability, it would be more relevant to ask "Why isn't the compiler *allowed* to determine if the `float` would be enough?" Fortunately, the accepted answer addressed this revised question. – JaMiT Oct 04 '20 at 21:20
1 Answers
1
The type of 0.5 in C++ is double. If you want a float you need to say 0.5f . This is part of the definition of C and C++.
Implied in your question is some desire for automatic type selection based on the number of digits in the value, e.g. we could use float for 0.5 but double for 0.123456789. This is not a tenable approach however, firstly because it is overly complex for compilers written in the 1980's, and second because it makes it harder to reason about code, e.g. what would be the type of 0.123 / 0.987
?

John Zwinck
- 239,568
- 38
- 324
- 436
-
Oh that makes sense. I didn't even think of that. Feeling ashamed that I've asked this question. Thanks! – AuthenticWolf Sep 21 '20 at 00:30