2013-09-02 3 views
5

Мой компилятор предупреждает: 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; 
    } 
} 

Это не определено?

+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 без каких-либо sequence point между ними. Так что это пример undefined behaviour.

+0

[страница] (http: // www. geeksforgeeks.org/sequence-points-in-c-set-1/), который вы запросили, - теперь доступно_ :-) –

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++]) 

вы оба приращением значения j с pattern [j++], и используя значение j в string [i + j]. Побочный эффект j++ не секвенирован относительно вычисления значения i + j. Так что это классическое неопределенное поведение.

Смежные вопросы