6

In quite a few languages like C# and D, 1f is be a valid way to declare a float literal, but in C++ the closest you can get by default is 1.f or 1.0f. However, this behaviour can be implemented using C++11's user-defined literal operators (even if it involves breaking the "underscores for user defined literals" rule). The following program (at least in g++ 4.9.2) works as expected, so I'm wondering if there's a good reason why 1f isn't valid syntax for float literals by default in C++.

#include <iostream>
#include <typeinfo>

constexpr float operator""f(unsigned long long int i){
    return static_cast<float>(i);
}

int main(){
    auto f1 = 1f;
    auto f2 = 1.f;

    if(typeid(f1) == typeid(f2))
        std::cout << "They're the same" << std::endl;

    return 0;
}
Mike Kinghan
  • 55,740
  • 12
  • 153
  • 182
Manpat
  • 144
  • 7
  • `static_cast` compiles when applied on an `unsigned long long` operand? – barak manos Jun 09 '15 at 07:00
  • @barakmanos Yes. It's equivalent (to my knowledge) to doing (float)i or float(i) – Manpat Jun 09 '15 at 07:02
  • 2
    http://stackoverflow.com/questions/3961467/why-isnt-0f-treated-as-a-floating-point-literal-in-c – Sergii Khaperskov Jun 09 '15 at 07:09
  • @SergiiKhaperskov Damn. I tried looking for a similar question but I guess I didn't try hard enough. Thanks – Manpat Jun 09 '15 at 07:12
  • "Good reason" is rather subjective, but the proposed duplicate's answers indicate implied, kinda arbitrary reason: `f` modifies a floating point literal to be `float` instead of `double`. `1` is not a floating point literal, so `f` can't modify it. – hyde Jun 09 '15 at 07:14
  • The *floating-suffix* characters are `f,l,F,L` (see 2.3.14 "Floating literals" in C++17 draft standard N4296). But we can't allow `1L` as a floating-point literal, because it's already an integer literal. So for consistency, `1f` is not allowed either. – TonyK Jun 09 '15 at 07:27

0 Answers0