はじめに
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の数式のほうが優先されます。
この警告は、()を用いて数式のほうが先に計算されることを明確にしなさいという警告です。
関連記事
- 【cppcheck】error: Undefined behavior: Variable 'xxx' is used as parameter and destination in s[n]printf().
- (warning) The 2nd memset() argument '8224' doesn't fit into an 'unsigned char'.
- 【C++】構造体のサイズとバイトアライメント
- C++のコードレビューで使いたい、コードの品質を向上させる3つの方法
- 【cppcheck】A pointer can not be negative so it is either pointless or an error to check if it is