为什么将unsigned short(乘)无符号short转换为signed int? [英] Why is unsigned short (multiply) unsigned short converted to signed int?

查看:166
本文介绍了为什么将unsigned short(乘)无符号short转换为signed int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在C ++ 11中将 unsigned short * unsigned short 转换为 int ?

int 太小,无法处理此代码行所示的最大值.

  cout<<USHRT_MAX * USHRT_MAX<<恩德尔 

MinGW 4.9.2上的溢出

 <代码> -131071 

因为(

解决方案

您可能想阅读有关隐式转换,尤其是有关数字促销的部分

较小整数类型的

Pr值(例如 char)可以转换为较大整数类型的prvalue(例如 int ).特别是算术运算符不接受小于 int 的类型作为参数

上面所说的是,如果在涉及int 的东西(如 unsigned short ).cppreference.com/w/cpp/language/operator_arithmetic>算术运算符(当然包括乘法运算),则值将提升为 int .

Why is unsigned short * unsigned short converted to int in C++11?

The int is too small to handle max values as demonstrated by this line of code.

cout << USHRT_MAX * USHRT_MAX << endl;

overflows on MinGW 4.9.2

-131071

because (source)

USHRT_MAX = 65535 (2^16-1) or greater*

INT_MAX = 32767 (2^15-1) or greater*

and (2^16-1)*(2^16-1) = ~2^32.


Should I expect any problems with this solution?

unsigned u = static_cast<unsigned>(t*t);


This program

unsigned short t;
cout<<typeid(t).name()<<endl;
cout<<typeid(t*t).name()<<endl;

gives output

t
i

on

gcc version 4.4.7 20120313 (Red Hat 4.4.7-16) (GCC)
gcc version 4.8.2 (GCC)
MinGW 4.9.2

with both

g++ p.cpp
g++ -std=c++11 p.cpp

which proves that t*t is converted to int on these compilers.


Usefull resources:

Signed to unsigned conversion in C - is it always safe?

Signed & unsigned integer multiplication

https://bytes.com/topic/c-sharp/answers/223883-multiplication-types-smaller-than-int-yields-int

http://www.cplusplus.com/reference/climits

http://en.cppreference.com/w/cpp/language/types


Edit: I have demonstrated the problem on the following image.

解决方案

You may want to read about implicit conversions, especially the section about numeric promotions where it says

Prvalues of small integral types (such as char) may be converted to prvalues of larger integral types (such as int). In particular, arithmetic operators do not accept types smaller than int as arguments

What the above says is that if you use something smaller than int (like unsigned short) in an expression that involves arithmetic operators (which of course includes multiplication) then the values will be promoted to int.

这篇关于为什么将unsigned short(乘)无符号short转换为signed int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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