Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 792
Agnel Kurian Avatar asked Oct 18 '10 17:10

Agnel Kurian


People also ask

Why do we write F in float in C?

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.

What is a floating-point literal in C?

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)

What is 0.0 F in C#?

'f' indicates that you want a float : 0 is an int. 0f is a float. 0.0 is a double.

What is an example of floating-point literal?

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)


1 Answers

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.

like image 119
zwol Avatar answered Oct 14 '22 14:10

zwol