私のコンパイラは警告します:operation on j may be undefined
Cコードは次のとおりです。
for(int j = 1; pattern[j] != '\0' && string[i] != '\0';){
if(string[i+j] != pattern[j++]){//this is on the warning
found = 0;
break;
}
}
それは未定義ですか?
私のコンパイラは警告します:operation on j may be undefined
Cコードは次のとおりです。
for(int j = 1; pattern[j] != '\0' && string[i] != '\0';){
if(string[i+j] != pattern[j++]){//this is on the warning
found = 0;
break;
}
}
それは未定義ですか?
はい。間にシーケンスポイントがなくstring[i+j] != pattern[j++]
、変数に基づいて2つの異なる実行があります。したがって、未定義の動作の例です。j
はい。C11 標準は、§6.5 で次のように述べています。
If a side effect on a scalar object is unsequenced relative to either a different
side effect on the same scalar object or a value computation using the value of the
same scalar object, the behavior is undefined. If there are multiple allowable
orderings of the subexpressions of an expression, the behavior is undefined if such
an unsequenced side effect occurs in any of the orderings.
ここで、比較では
if(string[i+j] != pattern[j++])
j
withの値をインクリメントし、inpattern [j++]
の値を使用しています。の副作用は、値の計算に関連して順序付けされていません。したがって、これは古典的な未定義の動作です。 j
string [i + j]
j++
i + j