One of the questions I’ve recently received is the fact that I find the letter f accompanied by numbers in C++: eg:
In general terms we can say that this number is a literal
8.04f . But why is there this f if the type is already a float? The answer is because by default every number with .(dot) C and C++ treat it as a double, so we need to make the
float type explicit.
Let’s take an example. Suppose you want to test the number pi:
At first you would say that the output of this code would be That is equal , but test and you will see that the output is: It is not equal .
Now if we add the f:
const float pi = 3.14f; it still wouldn’t be the same, if we keep the condition without the f.
But if we add the f in the condition, it would be equal to:
Or in both, which further prevents “human error”:
Alternatively you can also use the capital
F which works the same way.
It is highly recommended that you use this in all cases where accuracy is important, like games, for example.
There are also literal data for other types: long(
u), long unsigned(
ul), long long(
That’s all for today, they’re small daily doses that will always keep us in tune with C++.