分享方式:


編譯器警告 (層級 4) C4127

條件運算式是常數

備註

if 陳述式或 while 迴圈的控制運算式會評估為常數。 由於其常見慣用用法,從 Visual Studio 2015 update 3 開始,例如 1 或 true 未觸發警告等簡單常數,除非它們是運算式中作業的結果。

如果迴圈的控制 while 運算式是常數,因為迴圈在中間結束,請考慮將 while 迴圈取代為 for 迴圈。 您可以省略迴圈的初始化、終止測試和迴圈遞增 for ,這會導致迴圈無限,就像 while(1) ,而且您可以從 語句主體 for 結束迴圈。

範例

下列範例示範產生 C4127 的兩種方式,並示範如何使用 for 迴圈來避免警告:

// C4127.cpp
// compile with: /W4
#include <stdio.h>
int main() {
   if (true) {}           // OK in VS2015 update 3 and later
   if (1 == 1) {}         // C4127
   while (42) { break; }  // C4127

   // OK
   for ( ; ; ) {
      printf("test\n");
      break;
   }
}

當條件運算式中使用編譯時間常數時,也可以產生這個警告:

#include <string>

using namespace std;

template<size_t S, class T>
void MyFunc()
{
   if (sizeof(T) >= S) // C4127. "Consider using 'if constexpr' statement instead"
   {
   }
}

class Foo
{
   int i;
   string s;
};

int main()
{
   Foo f;
   MyFunc<4, Foo>();
}