5

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?

2013Asker
  • 2,008
  • 3
  • 25
  • 36

2 Answers2

10

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.

Dayal rai
  • 6,548
  • 22
  • 29
  • The [page](http://www.geeksforgeeks.org/sequence-points-in-c-set-1/) you requested is _now available_ :-) – 0xF1 Sep 02 '13 at 11:31
2

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.

verbose
  • 7,827
  • 1
  • 25
  • 40