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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With