2013-09-02 14 views
5

Moje kompilator ostrzega: operation on j may be undefinedCzy to nie jest zdefiniowane?

Oto kod 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; 
    } 
} 

Czy to niezdefiniowana?

+4

Gdzie jest "i" zadeklarowane/zainicjalizowane? –

+3

@MartinJames To nieistotne. – nos

+1

Możesz znaleźć [to pytanie] (http://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points?rq=1) interesującą lekturę. – WhozCraig

Odpowiedz

10

TAK. string[i+j] != pattern[j++] ma dwa różne wykonania w oparciu o zmienną j bez żadnego sequence point pomiędzy. Jest to więc przykład undefined behaviour.

+0

The [strona] (http: // www. geeksforgeeks.org/sequence-points-in-c-set-1/), o który prosiłeś, to jest dostępna available_ :-) –

2

Tak. Średnia C11 mówi w § 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. 

Tutaj, w porównaniu

if(string[i+j] != pattern[j++]) 

jesteś zarówno zwiększając wartość j z pattern [j++] i używając wartość j w string [i + j]. Efekt uboczny z j++ nie jest sekwencjonowany w stosunku do wartości obliczenia i + j. Jest to więc klasyczne niezdefiniowane zachowanie.

Powiązane problemy