为什么两个短裤相加会返回整数? [英] Why does the addition of two shorts return an int?

查看:66
本文介绍了为什么两个短裤相加会返回整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读了一个c ++教程,其中说算术运算符返回可能的最小数据类型(即,如果添加2个int,则返回类型将是int,如果添加了float和double则返回类型将是double)。但是,它也表示对短裤的算术运算会返回整数。考虑到short占用的内存少于int的内存,为什么会发生这种情况?教程有误吗?本教程适用于c ++ 11,所以也许在c ++ 14中已弃用?谢谢!

I read a c++ tutorial that says arithmetic operators return the smallest data type possible (i.e. if 2 ints are added the return type will be int, if a float and a double are added the return type will be double). However, it also said that arithmetic operations on shorts return ints. Considering that shorts take up less memory than ints, why does that happen? Was the tutorial mistaken? The tutorial was for c++11, so maybe that has been deprecated in c++14? Thanks!

推荐答案


考虑到短裤比int占用更少的内存,为什么会这样?

Considering that shorts take up less memory than ints, why does that happen?

这是因为标准这样说。


教程是否弄错了?

Was the tutorial mistaken?

否。

从C ++ 11标准(请注意通常的算术转换位):

From the C++11 Standard (note the usual arithmetic conversion bit):


5个表达式

...

9许多二进制运算符预期算术或枚举类型的操作数会以类似方式导致转换和产生结果类型。目的是产生一个通用类型,它也是结果的类型。这种模式称为常用算术转换,其定义如下:

9 Many binary operators that expect operands of arithmetic or enumeration type cause conversions and yield result types in a similar way. The purpose is to yield a common type, which is also the type of the result. This pattern is called the usual arithmetic conversions, which are defined as follows:

...

-否则,将对两个操作数执行积分提升(4.5)。

— Otherwise, the integral promotions (4.5) shall be performed on both operands.

积分奖励在标准中定义为:


4.5整体促销

1除 bool char16_t ,<$ c $之外的整数类型的prvalue c> char32_t 或 wchar_t 的整数转换排名(4.13)小于 int int 可以表示源类型的所有值,则可以将$ c>转换为类型 int 的prvalue。否则,源prvalue可以转换为 unsigned int 类型的prvalue。

1 A prvalue of an integer type other than bool, char16_t, char32_t, or wchar_t whose integer conversion rank (4.13) is less than the rank of int can be converted to a prvalue of type int if int can represent all the values of the source type; otherwise, the source prvalue can be converted to a prvalue of type unsigned int.

按照上述,在将某些二进制运算符应用于操作数之前,将 short 提升为 int

As per above a short is promoted to an int before some of the binary operators are applied to the operands.

关于运算符 + -的部分专门提到通常对操作数执行算术转换:

The section about operators + and - specifically mentions that usual arithmetic conversions are performed on the operands:


5.7加法运算符

1附加运算符 + -组从左到右。通常对算术或枚举类型的操作数执行算术转换。

1 The additive operators + and - group left-to-right. The usual arithmetic conversions are performed for operands of arithmetic or enumeration type.

这篇关于为什么两个短裤相加会返回整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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