Introduce intermediate variable so that compiler will not complain
authorArtem Zhmurov <zhmurov@gmail.com>
Thu, 22 Oct 2020 13:39:03 +0000 (16:39 +0300)
committerMark Abraham <mark.j.abraham@gmail.com>
Thu, 22 Oct 2020 15:07:09 +0000 (15:07 +0000)
Some compilers complain about the shift being larger than the shifted
variable, even though it is never executed in this case. This introduces
an intermediate shift variable that is explicitely set to zero in this case.

Issue #3752.

src/gromacs/random/seed.cpp

index b1fc061fd11810a38ae102a359125d712db67f67..79f67c9cfc2edbf572ba5daf4dcff6e4f20dbbd7 100644 (file)
@@ -91,14 +91,12 @@ static uint64_t makeRandomSeedInternal(GeneratorType& gen)
             std::numeric_limits<typename GeneratorType::result_type>::digits;
 
     uint64_t result = static_cast<uint64_t>(gen());
-    // This conditional is needed so that compiler understands that what follows is a dead branch
-    // and not complains about shift larger than number of bits in the result.
-    if (resultBits < numBitsInRandomNumber)
+    // This is needed so that compiler understands that what follows is a dead branch
+    // and not complains about shift count larger than number of bits in the result.
+    constexpr std::size_t shiftCount = (resultBits < numBitsInRandomNumber) ? numBitsInRandomNumber : 0;
+    for (std::size_t bits = numBitsInRandomNumber; bits < resultBits; bits += numBitsInRandomNumber)
     {
-        for (std::size_t bits = numBitsInRandomNumber; bits < resultBits; bits += numBitsInRandomNumber)
-        {
-            result = (result << numBitsInRandomNumber) | static_cast<uint64_t>(gen());
-        }
+        result = (result << shiftCount) | static_cast<uint64_t>(gen());
     }
     return result;
 }