Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

Floating-point literal and the f suffix

A floating-point literal writes a numeric value directly in source code. The suffix f or F gives it type float; without a suffix it has type double, and with l or L it has type long double.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

1.0f; 1.0F; .5f; 1.f; 1e3f; 0x1.8p+1f

A floating-point literal writes a number in source code. The suffix f or F selects type float, as in 1.0f. Without a suffix, 1.0 has type double; 1.0L has type long double. The suffix determines the literal's own type, not the declared variable's type.

Decimal notation requires a decimal point or an exponent: .5f, 1.f, and 1e3f are valid, but 1f is not a valid floating-point literal. An exponent introduced by e or E denotes a power of 10. Hexadecimal notation starts with 0x or 0X and requires an exponent introduced by p or P, denoting a power of 2: 0x1.8p+1f represents 3.

The f suffix does not guarantee exact representation of every decimal number: a value that cannot be represented exactly may be rounded. In the example, static_assert checks types at compile time, and the program should print 3 followed by a newline. The displayed source was run unchanged in an isolated environment, and its standard output matched the expected output exactly.

Reference identifiers covered by this entry: Floating-point literal suffix f.

Examples

#include <iostream>
#include <type_traits>

int main() {
    static_assert(std::is_same_v<decltype(1.0f), float>);
    static_assert(std::is_same_v<decltype(1.0F), float>);
    static_assert(std::is_same_v<decltype(1.0), double>);
    static_assert(std::is_same_v<decltype(1.0L), long double>);

    constexpr float value = 0x1.8p+1f;
    static_assert(value == 3.0f);
    std::cout << value << '\n';
}

Result

3

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources