【问题标题】:When i use auto bi = 123456789, in C++, is it always assigned as an int?当我在 C++ 中使用 auto bi = 123456789 时,它总是分配为 int 吗?
【发布时间】:2016-10-30 01:18:34
【问题描述】:

如果我希望 bi 成为 long int,是否不能使用 auto,因为它总是分配为 int?

【问题讨论】:

  • 为什么你认为它“赋值为 int”?
  • 如果你用引号括起来,它肯定不会是一个 int。这将是char const*(我认为)。 --- 您可以检查变量的类型,如提到的here
  • 如果你特别希望它是long,为什么不直接告诉编译器long bi =
  • 字符串就是字符串。 C++ 在字符串中的数字和实际数字之间没有自动转换。
  • 您要查找的关键字是“整数文字”。有很多后缀可以用来控制类型。

标签: c++ gcc


【解决方案1】:

一些选项:

auto bi = "123456789";          // const char*
auto bi2 = 12345;               // int
auto bi3 = 123456789;           // int (when int is 32 bits or more )
auto bi4a = 123456789L;         // long
auto bi4b = 178923456789L;      // long long! (L suffix asked for long, but got long long so that the number can fit)
auto bi5a = 123456789LL;        // long long
auto bi5b = 123456784732899;    // long long (on my system it is long long, but might be different on ILP64; there is would just be an int)
auto bi6 = 123456789UL;         // unsigned long
auto bi7 = 123456789ULL;        // unsigned long long

以上所有示例都取决于您使用的系统。

在标准中,[lex.icon] 表 5 — 整数文字的类型 被引用:

整数字面量的类型是对应列表的第一个 在表5中可以表示其值。

如果我们查看表中的十进制文字,我们会发现即使UL 后缀的效果也取决于可以容纳的大小:

【讨论】:

  • 很棒的答案。您可以更进一步,添加long long 的示例。
  • 还有 longlong (ll) 和 unsigned long long (ull)。
  • 我试图找到一个 SO 问题,其中从描述如何为文字选择类型的标准中提到了该表。
  • @flatmouse:你必须深入到 C 标准才能找到范围值。
  • 请注意,在 ILP64 架构上,bi5b 将只是 int(即 long long 不正确);请参阅 (unix.org/whitepapers/64bit.html)。
猜你喜欢
  • 2011-02-20
  • 1970-01-01
  • 2010-11-08
  • 1970-01-01
  • 1970-01-01
  • 2011-04-05
相关资源
最近更新 更多