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

2 回答 2

10

的。string[i+j] != pattern[j++]基于变量进行两次不同的执行,中间j没有任何序列点。所以这是未定义行为的例子。

于 2013-09-02T11:26:28.377 回答
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++])

您既要增加jwith的值pattern [j++],又要使用jin的值string [i + j]。的副作用j++与值计算无关i + j。所以这是典型的未定义行为。

于 2013-09-02T11:39:04.617 回答