(style) Redundant condition: If ‘x > 11’, the comparison ‘x > 10’ is always true.
冗長な条件。x > 11’の場合、比較の’x > 10’は常に真。
[(style)redundantCondition]
■1.制御が来た時if文は必ず成立する
#include <stdio.h>
void f1(int x) {
if(x > 11){
if(x > 10) //★ここに制御が来た時if文は必ず成立する
printf("来る:%s:%d\n",__func__,__LINE__);
else
printf("★来ない1 x=%d\n",x);
} else {
if(x <= 11) //★ここに制御が来た時if文は必ず成立する
printf("来る:%s:%d\n",__func__,__LINE__);
else
printf("★来ない2 x=%d\n",x);
}
}
■2.制御が来た時if文は必ず成立しない
void f2(int x) {
if(x > 10){
printf("来る:%s:%d\n",__func__,__LINE__);
return ;
}
if(x > 11){ //★ここに制御が来た時if文は必ず成立しない
printf("★来ない3 x=%d\n",x);
return ;
}
}
■3.第二条件だけで充分
int f3(int x) {
if(x > 10 && x > 11)//★NG
return 1;
return 0;
}
cppcheckとclang-tidyが警告してくれます
■4.決して実行されないコード
void f4(int b){
char *s = NULL;
if (b) {
s = "s設定経路はreturnする";
printf("来る:%s:%d:%s\n",__func__,__LINE__,s);
return;
}
if (s != NULL) {
printf("★来ない4 s=%s\n",s);
}
}
int main(void){
for(int i = -5 ; i < 15 ;i++){
f1(i);f2(i);f3(i);
}
f4(0);f4(1);
}
参考: