这是未定义的吗?

5

我的编译器警告: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;
    }
}

这是未定义的吗?


4
“i” 变量在哪里被声明/初始化? - Martin James
3
@MartinJames 这与问题无关。 - nos
1
你可能会发现这个问题很有趣。 - WhozCraig
1
我认为问题与序列点有关。 - 0xF1
通常情况下,当有人问C语言中某个东西是否是未定义行为时,它通常就是。 - harold
显示剩余3条评论
2个回答

10

是的。在变量j之间没有任何序列点的情况下,string[i+j] != pattern[j++]具有两种不同的执行方式。因此,这是一个未定义行为的示例。


您请求的页面现在已经可用 :-) - 0xF1

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的值。 j++的副作用与值计算i + j之间没有顺序关系,所以这是经典的未定义行为。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接