[英]pointers incrementing problem inside if..else
As a part of a fairly complex function, I wrote this bit of code:作为相当复杂的 function 的一部分,我编写了这段代码:
if( (((int)*(pointer-11 .... ) //It is too long and complex
{
*(pointer++)=*(pointer-12)+1;
}
else
{
*(pointer++)=*(pointer-12);
}
The if part works well, but the else parts works like: if 部分运行良好,但 else 部分的工作方式如下:
*(pointer++)=*(pointer-11);
When I put the incrementing code separate from the actual line,当我将递增代码与实际行分开时,
if( .... )
{
*(pointer)=*(pointer-12)+1;
}
else
{
*(pointer)=*(pointer-12);
}
pointer++;
It works perfectly.它完美地工作。 But code on top should work too, right?但是上面的代码也应该可以工作,对吧? Any thoughts?有什么想法吗?
*(pointer++)=*(pointer-12);
is undefined behavior.是未定义的行为。 There is no sequence point here, so you don't know if the left or right part of the =
will get evaluated first.这里没有序列点,所以你不知道=
的左边还是右边部分将首先被评估。
Since it's undefined behavior, the compiler might do anything, but these are pretty sensible interpretations of it:由于它是未定义的行为,编译器可能会做任何事情,但这些是对它的非常明智的解释:
// Left gets evaluated first
*(pointer)=*((pointer+1)-12);
pointer++;
// Right gets evaluated first
*(pointer)=*(pointer-12);
pointer++;
Note that this has nothing to do with pointers.请注意,这与指针无关。 The expression x++ <op> x
causes undefined behavior irregardless of what type x
has and what operator <op>
is.表达式x++ <op> x
导致未定义的行为,无论x
具有什么类型以及运算符<op>
是什么。 (That's maybe not 100% true, but you better avoid these expressions anyway) (这可能不是 100% 正确,但无论如何你最好避免使用这些表达方式)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.