C++中文字面类型的目的是什么?

huangapple go评论69阅读模式
英文:

What is the point of types of literals in C++?

问题

我是C++的新手,正在使用C++ Primer学习。

对我来说,变量像longlong long这样的“子类型”对于int来说是有意义的,这样它们可以容纳更大的值,即使它们被初始化为一个不那么大的值。

但我似乎无法理解为什么需要覆盖整数字面量(例如42)的默认类型,使其成为long long而不是默认的int?毕竟字面量永远不会容纳另一个值,因为它实际上是一个常量。

英文:

I'm new to C++ and I'm using C++ Primer to study.

To me, it makes sense for variables to have "sub-types" like long and long long for int, so that they can accommodate larger values, even if they're initialized with a not so large value.

But I can't seem to wrap my head around why one might need to override the default type of, say, an integer literal such as 42 to make it long long instead of the default int? It's not like the literal will ever have to hold another value, since it's practically a constant.

答案1

得分: 6

当您直接在表达式中使用字面值(而不仅仅是用指定类型初始化变量),那么字面值的类型将变得重要,因为算术表达式受特定整数类型的影响。

例如:

1 << 32

在这里,1 的类型是 int,因此在一个 int 宽度为 32 位的系统上,这将导致未定义的行为:您不能将整数左移超过 w-1,其中 w 是它的宽度。

另一方面,

1LL << 32

是可以保证正常工作的,因为 1LL 的类型是 long long,并且该类型保证至少为 64 位宽度。

类似地,重载解析可能会根据操作数/参数的类型选择不同的函数来调用。因此,使用 1LL 作为参数而不是 1 可能会调用具有不同行为的不同重载函数。

英文:

When you use a literal directly in an expression (rather than just initializing a variable with a specified type from it), then the type of the literal will be important because arithmetic expressions are affected by the specific integer types.

For example:

1 &lt;&lt; 32

Here 1 has type int and so, on a system where int is 32 bit wide, this will have undefined behavior: You can't left-shift an integer more than by w-1 where w is its width.

On the other hand

1LL &lt;&lt; 32

is guaranteed to be fine, because 1LL has type long long and that type is guaranteed to be at least 64 bit wide.

Similarly, overload resolution may choose different functions to call depending on the type of an operand/argument. So using 1LL as an argument instead of 1 may call a different overload with different behavior.

huangapple
  • 本文由 发表于 2023年7月24日 18:17:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76753492.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定