为什么不是“0f"?在 C++ 中被视为浮点文字? [英] Why isn't "0f" treated as a floating point literal in C++?

查看:61
本文介绍了为什么不是“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 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.

添加了 FL 后缀,用于传达类型信息浮动常量,很像 L 后缀对长整数的作用.默认为了与先前的做法兼容,浮动常量的类型保持为 double.小写 fl 也可以作为后缀.

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++ 中被视为浮点文字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆