为什么 0f
在 C++ 中不被视为浮点字面量?
#include <iostream>
using namespace std;
int main(){
cout << 0f << endl;
return 0;
}
编译上面给了我
C2509 (syntax error: 'bad suffix on number')
使用 VS2008。
最佳答案
如果此设计决策有明确说明的原因,则应在 C99“基本原理”文档中(C++ 从 C 中逐字复制所有这些内容,而没有重新考虑)。但是没有。这就是关于“f”后缀的所有内容:
§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.
不过,是一个隐含的原因。请注意措辞:“已添加 ... 后缀以使用 float 常量传达类型信息。”该标准的作者认为数字常量在您到达后缀时已经明确地是整数或 float 。后缀仅用于类别内的额外特异性,它不能将数字从一个类别翻转到另一个类别。这得到了实际语法(C99 §6.4.4)的支持,该语法首先将数字常量定义为整数常量或浮点常量,然后定义单独的类每个的后缀。
关于c++ - 为什么 "0f"在 C++ 中不被视为浮点文字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3961467/