小さい頃はエラ呼吸

いつのまにやら肺で呼吸をしています。


【cppcheck】(style) Clarify calculation precedence for '+' and '?'.

はじめに

C++の静的解析ツール「cppcheck」でソースコードを静的解析した場合に、以下の警告がでることがあります。

(style) Clarify calculation precedence for '+' and '?'.

cppcheckのバージョン
  • v1.66
サンプルプログラム

以下のソースプログラムを解析にかけると表示されます。

#include "stdafx.h"
#include <windows.h>
#include <stdio.h>

int Count()
{
  return 1;
}

int _tmain(int argc, _TCHAR *argv[])
{
  int result = 0;
  bool flag = false;
  result = Count() + flag ? 1 : 2;  //-> (style) Clarify calculation precedence for '+' and '?'.
  //result = (Count() + flag) ? 1 : 2;

  printf("%d\n", result);

  return 0;
}

上記のように、数式による演算の結果を三項演算子で比較する場合、?による比較よりも先に、Count() + flagの数式のほうが優先されます。
この警告は、()を用いて数式のほうが先に計算されることを明確にしなさいという警告です。