Why isn't 0f
treated as a floating point literal in C++?
#include <iostream>
using namespace std;
int main(){
cout << 0f << endl;
return 0;
}
Compiling the above gives me
C2509 (syntax error: 'bad suffix on number')
using VS2008.
In c a value of 1 is an integer and 1.0 is a double, you use f after a decimal number to indicate that the compiler should treat it as a single precision floating point number.
Floating-point literals are numbers that have a decimal point or an exponential part. They can be represented as: Real literals. Binary floating-point literals. Hexadecimal floating-point literals (C only)
'f' indicates that you want a float : 0 is an int. 0f is a float. 0.0 is a double.
Hexadecimal floating-point literals (C only)Real hexadecimal floating-point constants, which are a C99 feature, consist of the following parts. The significant part represents a rational number and is composed of the following: a sequence of hexadecimal digits (whole-number part)
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 onlyfloat
operands to be performed infloat
arithmetic rather thandouble
, a method of expressing explicitfloat
constants is desirable. Thelong double
type raises similar issues.The
F
andL
suffixes have been added to convey type information with floating constants, much like theL
suffix does for long integers. The default type of floating constants remains double for compatibility with prior practice. Lower-casef
andl
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With