Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

The `f` suffix on floating-point literals

Append `f` or `F` to make a floating-point literal a `float` rather than the default `double`. This affects type deduction and overload resolution.

Version: ISO C++23; implementation support may vary

Syntax

1.0f        // float
1.0F        // float
1e0f        // float: decimal exponent, no decimal point
0x1p0f      // float: hexadecimal form with a binary exponent
1.0         // double
1.0L        // long double

The floating literal suffix (f) is written directly at the end of a floating-point literal. Both 1.0f and 1.0F have type float. The suffix is part of the literal, not a cast. With no suffix, 1.0 has type double; 1.0l and 1.0L have type long double.

A decimal spelling needs a point or an exponent: 1.0f and 1e0f are valid, but 1f is not a standard spelling of a float literal. A hexadecimal spelling requires a binary exponent introduced by p or P, as in 0x1p0f.

In auto a = 1.0f;, the compiler deduces float; with 1.0 it would deduce double. When show(float) and show(double) are both available, the exact type match wins. The suffix does not force the type of a whole expression: 1.0f + 2.0 has type double.

0.1f gives a float value that need not equal the mathematical value 0.1 exactly. Promoting it to double later preserves that value but cannot recover lost precision. By contrast, float x = 0.1; converts a double literal to float. The suffix f does not guarantee IEEE 754 binary32. In C++23, f32 denotes the distinct type std::float32_t and is available only if the implementation supports that extended type.

Examples

#include <iostream>
#include <type_traits>

void show(float)  { std::cout << "float\n"; }
void show(double) { std::cout << "double\n"; }

int main() {
    auto a = 1.0f;
    auto b = 1.0;
    static_assert(std::is_same_v<decltype(a), float>);
    static_assert(std::is_same_v<decltype(b), double>);

    show(a);
    show(b);
}

Result

float
double

The `static_assert` declarations check the types deduced by `auto`. Each `show` call selects the overload with the exact parameter type, so the expected output is `float` followed by `double`, on separate lines.

Related lessons

  • C++ · Lesson 32 · Advanced · Version: 3

Sources