我的编译器发出警告: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;
}
}
那是不确定的?
答案 0 :(得分:10)
是即可。 string[i+j] != pattern[j++]
基于变量j
执行了两次不同的执行,其间没有任何sequence point。所以这是undefined behaviour的例子。
答案 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
没有排序。所以这是经典的未定义行为。