Search code examples
c++floating-pointintegerliterals

Why cannot you use a 'f' suffix directly after an integer?


While writing a C++ application, I have found out that I cannot use the f suffix (e.g. 3f) as Visual Studio shows me the following error: "Literal operator not found". The problem, of course, disappears when I use the .f suffix(e.g. 3.f). Why is that?


Solution

  • Here are the rules from the standard:

    floating-point-literal:
        decimal-floating-point-literal
        hexadecimal-floating-point-literal
    
    decimal-floating-point-literal:
        fractional-constant exponent-part-opt floating-point-suffix-opt
        digit-sequence exponent-part floating-point-suffix-opt
    
    fractional-constant:
        digit-sequence-opt . digit-sequence
        digit-sequence .
    
    exponent-part:
        e sign-opt digit-sequence
        E sign-opt digit-sequence
    
    floating-point-suffix: one of
        f  l  F  L
    

    As you can see, the . has to be always included in a decimal floating point constant, if there is no exponent part.

    The K&R book explains this as:

    Floating-point constants contain a decimal point ( 123.4 ) or an exponent ( 1e-2 ) or both; their type is double, unless suffixed. The suffixes f or F indicate a float constant; l or L indicate a long double .

    So, the thinking is, that f or l modifies an already floating-point constant (double) to have the type of float or long double. The suffix itself doesn't make a non-floating-point constant to a floating-point constant.