我的编译器警告:j的操作可能是未定义的
下面是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;
}
}
这是未定义的吗?
我的编译器警告:j的操作可能是未定义的
下面是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;
}
}
这是未定义的吗?
可以的。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
的值。 j++
的副作用与值计算i + j
之间没有顺序关系,所以这是经典的未定义行为。