2013-09-02 49 views
5

私のコンパイラが警告しこれは未定義ですか?ここで<code>operation on j may be undefined</code></p> <p>を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; 
    } 
} 

が未定義ということですか?

+4

「i」はどこに宣言/初期化されていますか? –

+3

@MartinJamesそれは無関係です。 – nos

+1

[この質問](http://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points?rq=1)に興味深い記事があります。 – WhozCraig

答えて

10

はいstring[i+j] != pattern[j++]は、変数jに基づいて2つの異なる実行があり、その間にはsequence pointがありません。したがって、それはundefined behaviourの例です。

+0

[ページ](http:// www。 geeksforgeeks.org/sequence-points-in-c-set-1/)あなたがリクエストしたのは_now available_ :-)です –

2

はい。 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++]) 

にあなたは両方のpattern [j++]jの値をインクリメントし、string [i + j]jの値を使用しています。 j++の副作用は、値計算i + jに対して順序付けされていません。これは古典的な未定義の動作です。

関連する問題