Why isn#39;t quot;0fquot; treated as a floating point literal in C++?(为什么不是“0f?在 C++ 中被视为浮点文字?)
问题描述
为什么 0f
在 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;
}
编译上面给了我
C2509(语法错误:'数字后缀错误')
C2509 (syntax error: 'bad suffix on number')
使用 VS2008.
推荐答案
如果这个设计决定有明确说明的原因,它会在 C99基本原理"文档中(C++ 从 C 中逐字复制所有这些东西,没有重新考虑它).但是没有.这就是关于f"后缀的所有内容:
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:
与现有实践一致,浮点常量定义为键入 double
.由于 C89 允许表达式仅包含 float
操作数在 float
算术而不是 double
中执行,这是一种表达明确的 float
常量是可取的.long double
类型引发了类似的问题.
§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.
添加了 F
和 L
后缀,用于传达类型信息浮动常量,很像 L
后缀对长整数的作用.默认为了与先前的做法兼容,浮动常量的类型保持为 double.小写 f
和 l
也可以作为后缀.
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.
不过,是一个隐含的原因.请注意措辞:已添加 ... 后缀以使用浮动常量传达类型信息."该标准的作者认为数字常量在您到达后缀时已经明确地是整数或浮点数.后缀仅用于类别内的额外特异性,它不能将数字从一个类别翻转到另一个类别.这得到了实际语法(C99 §6.4.4)的支持,该语法首先将数字常量定义为整数常量或浮点常量,然后定义单独的类每个的后缀.
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.
这篇关于为什么不是“0f"?在 C++ 中被视为浮点文字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么不是“0f"?在 C++ 中被视为浮点文字?


基础教程推荐
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09