Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this undefined?

My compiler warns: operation on j may be undefined

Here's the C code:

for(int j = 1; pattern[j] != '\0' && string[i] != '\0';){
    if(string[i+j] != pattern[j++]){//this is on the warning
        found = 0;
        break;
    }
}

Is that undefined?

like image 953
2013Asker Avatar asked Sep 02 '13 11:09

2013Asker


2 Answers

YES. string[i+j] != pattern[j++] is having two different execution based on variable j without any sequence point in between. So it is example of undefined behaviour.

like image 191
Dayal rai Avatar answered Sep 29 '22 04:09

Dayal rai


Yes. The C11 standard says in §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.

Here, in the comparison

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

you are both incrementing the value of j with pattern [j++], and using the value of j in string [i + j]. The side effect of j++ is not sequenced relative to the value computation i + j. So this is classic undefined behavior.

like image 32
verbose Avatar answered Sep 29 '22 03:09

verbose