[英]Why is there a narrowing conversion warning from int to short when adding shorts? (C++)
I have a code similar to this for the following array:对于以下数组,我有一个类似于此的代码:
long int N = 424242424242; //random number
short int* spins = new short int spins[N];
std::fill(spins, spins+N, 1);
Now let's suppose for some reason I want to add a couple of elements of that array into a short int called nn_sum:现在让我们假设出于某种原因我想将该数组的几个元素添加到一个名为 nn_sum 的短整数中:
short int nn_sum = spins[0] + spins[1];
However, when I do this on CLion IDE, Clang-Tidy marks it yellow and tells me:然而,当我在 CLion IDE 上执行此操作时,Clang-Tidy 将其标记为黄色并告诉我:
Clang-Tidy: Narrowing conversion from 'int' to signed type 'short' is implementation-defined
Why is this happening?为什么会这样? Why is there any narrowing at all?
为什么会缩小? Does C++ convert the shorts to ints when adding them?
C++ 添加时是否将短裤转换为整数? If so why, and is there something I can do to make it work better?
如果是这样,为什么,我可以做些什么来让它更好地工作? Maybe even ditch the shorts entirely?
甚至可能完全抛弃短裤?
Keep in mind that I have code like this in a very computationally intensive part of the application so I want to make it as efficient as possible.请记住,我在应用程序的计算密集型部分中有这样的代码,因此我想让它尽可能高效。 Any other suggestion would also be appreciated.
任何其他建议也将不胜感激。
This happens because of integer promotion.发生这种情况是因为 integer 促销。 The result of adding two
short
values is not short
, but int
.添加两个
short
值的结果不是short
,而是int
。
You can check this with cppinsights.io:您可以使用 cppinsights.io 进行检查:
short a = 1;
short b = 2;
auto c = a + b; // c is int
Demo: https://cppinsights.io/s/68e27bd7演示: https://cppinsights.io/s/68e27bd7
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.