Perry Programmer
Perry Programmer

Reputation: 29

Data type float

While declaring a variable of type float, is it necessary to write f towards the end of the value? For example, float amount = .01 and float amount = 0.01f, here what does the f mean and how does it make any difference?Also, what is the role of #include library file here.

Upvotes: 1

Views: 627

Answers (4)

That depends... You can do for example:

1)

float f = 3.14f;

In this case the literal 3.14 is explicitly given as a float... so everything is ok

2)

float f = 3.14;

In this case 3.14 is actually a double, but the variable f is declared as a float...so when compiling, the number will be casted to a float with the loss precision consequences of that case...

You could since c++11

auto f = 3.14;

Or auto f{3,14};

In both cases the compiler takes exactly the type of the literal...(both are doubles)

Upvotes: 0

Bathsheba
Bathsheba

Reputation: 234875

It's not necessary: the compiler will make an appropriate numerical conversion for you.

0.01f is a literal of float type, whereas 0.01 is a double type.

Occasionally you need to descriminate explicitly especially when working with templates or overloaded functions:

void foo(const float&){
    // Pay me a bonus
}

void foo(const double&){
    // Reformat my disk
}

int main(){
    foo(1.f);
}

Finally, if you're leading towards using a float over a double, then do read through this: Is using double faster than float?

Upvotes: 5

lubgr
lubgr

Reputation: 38325

It depends on how you define your variable. When specifying the type float in the definition, adding a trailing f is not necessary:

float amount = 0.1; /* This is fine, compiler knows the type of amount. */

Adding a superfluous literal here (float amount = 0.1f;) might even be considered bad practice, as you repeat the type information, resulting in more edits when the type is changed.

In the context of type deduction though, you have to give the f literal:

auto amount = 0.1f; /* Without the literal, compiler deduces double. */

There are more subtle contexts in which type deduction occurs, e.g.

std::vector<float> vecOfFloats;

/* ... */

std::accumulate(vecOfFloats.cbegin(), vecOfFloats.cend(), 0.1f);

Here, the third argument is used to deduce the type on which std::accumulate operates. If you just call it like std::accumulate(..., 0.1);, a double to float conversion takes place for every element in vecOfFloats.

Upvotes: 2

Caleth
Caleth

Reputation: 63277

.01 is a double literal. There is an implicit conversion to float in the initialisation

float amount = .01;

.01f is a float literal. There is no conversion in the initialisation

float amount = .01f;

Upvotes: 0

Related Questions