对于以下数组,我有一个类似于此的代码:
long int N = 424242424242; //random number
short int* spins = new short int spins[N];
std::fill(spins, spins+N, 1);
现在,让我们假设出于某种原因,我想将数组的几个元素添加到一个名为nn_sum的短int中:
short int nn_sum = spins[0] + spins[1];
但是,当我在CLion IDE上这样做时,Clang将其标记为黄色并告诉我:
Clang-Tidy: Narrowing conversion from 'int' to signed type 'short' is implementation-defined
为什么会发生这种情况?为什么要缩小范围呢?在添加短裤时,C++是否将其转换为ints?如果是这样的话,我还能做些什么让它更好地工作吗?甚至把短裤全扔了?
请记住,在应用程序中计算非常密集的部分中有这样的代码,因此我希望使其尽可能高效。任何其他建议也将不胜感激。
发布于 2022-04-12 12:25:24
这是因为整数提升。添加两个short
值的结果不是short
,而是int
。
您可以使用cppinsights.io来检查这一点:
short a = 1;
short b = 2;
auto c = a + b; // c is int
https://stackoverflow.com/questions/71842556
复制相似问题