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++ 中被视为浮点文字?
基础教程推荐
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- C++,'if' 表达式中的变量声明 2021-01-01
- 设计字符串本地化的最佳方法 2022-01-01
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31