Why isn't “0f” treated as a floating point literal in C++?

后端 未结 6 649
暖寄归人
暖寄归人 2020-12-03 21:19

Why isn\'t 0f treated as a floating point literal in C++?

#include 

using namespace std;

int main(){
  cout << 0f <&l         


        
6条回答
  •  盖世英雄少女心
    2020-12-03 21:50

    If there was an explicitly stated reason for this design decision, it would be in the C99 "Rationale" document (C++ copied all this stuff verbatim from C without reconsidering it). But there isn't. This is everything that's said about the 'f' suffix:

    §6.4.4.2 Floating constants

    Consistent with existing practice, a floating-point constant is defined to have type double. Since C89 allows expressions that contain only float operands to be performed in float arithmetic rather than double, a method of expressing explicit float constants is desirable. The long double type raises similar issues.

    The F and L suffixes have been added to convey type information with floating constants, much like the L suffix does for long integers. The default type of floating constants remains double for compatibility with prior practice. Lower-case f and l are also allowed as suffixes.

    There is an implied reason, though. Note the wording: "the ... suffixes have been added to convey type information with floating constants." The authors of the standard were thinking of numeric constants as already being unambiguously either integer or floating point by the time you get to the suffix. The suffix is only for extra specificity within the category, it can't flip a number from one category to another. This is backed up by the actual grammar (C99 §6.4.4) which first defines numeric constants as being either integer-constants or floating-constants, and then defines separate classes of suffixes for each.

提交回复
热议问题