[英]Why is there a narrowing conversion warning from int to short when adding shorts? (C++)
對於以下數組,我有一個類似於此的代碼:
long int N = 424242424242; //random number
short int* spins = new short int spins[N];
std::fill(spins, spins+N, 1);
現在讓我們假設出於某種原因我想將該數組的幾個元素添加到一個名為 nn_sum 的短整數中:
short int nn_sum = spins[0] + spins[1];
然而,當我在 CLion IDE 上執行此操作時,Clang-Tidy 將其標記為黃色並告訴我:
Clang-Tidy: Narrowing conversion from 'int' to signed type 'short' is implementation-defined
為什么會這樣? 為什么會縮小? C++ 添加時是否將短褲轉換為整數? 如果是這樣,為什么,我可以做些什么來讓它更好地工作? 甚至可能完全拋棄短褲?
請記住,我在應用程序的計算密集型部分中有這樣的代碼,因此我想讓它盡可能高效。 任何其他建議也將不勝感激。
發生這種情況是因為 integer 促銷。 添加兩個short
值的結果不是short
,而是int
。
您可以使用 cppinsights.io 進行檢查:
short a = 1;
short b = 2;
auto c = a + b; // c is int
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.