Nayaz Pasha C M
PRO
2 months ago
Nayazcountry asked

Since I declared n as a float using float n = 1.2, why do I need to add f at the end?

Udayan Shakya
Expert
last month
Udayan Shakya answered

Hi Nayaz,

Good question. You’re right that the code will still run without the f, but here’s what’s really happening:

When you write:

float n = 1.2;

the value 1.2 is treated as a double by default. Then it's converted to a float, which can lead to a small precision loss — because double uses 8 bytes, while float uses only 4.

If you write:

float n = 1.2f;

you’re telling the compiler directly: “this is a float value,” and it avoids any unnecessary type conversion or warning.

So while the f isn’t strictly required, it’s considered good practice when assigning float literals.

If you have more questions, I am here to help.

C++
This question was asked as part of the Learn C++ Basics course.