The below code works as expected on Windows but when built with Clang 6.0 and running on an Ubuntu server it does not work. The CurAnimIndex is an int32 and has the value 2147483647 (max int). I would expect it to enter the branch since the value of CurAnimIndex after the increment should be a negative number, however it does not.
CurAnimIndex++;
if (CurAnimIndex >= AnimSelectorDatas.Num() || CurAnimIndex < 0)
{
CurAnimIndex = 0;
}
0x000000000411a12f mov 0x0(%r13),%eax
0x000000000411a133 lea 0x1(%rax),%ecx
0x000000000411a136 movslq 0x10(%r13),%r15
0x000000000411a13a xor %ebp,%ebp
0x000000000411a13c cmp %r15d,%ecx
0x000000000411a13f cmovge %ebp,%ecx
0x000000000411a142 cmp $0xffffffff,%eax
0x000000000411a145 cmovl %ebp,%ecx
0x000000000411a148 mov %ecx,0x0(%r13)
0x000000000411a14c mov 0x8(%r13),%r12 enter code here
CurAnimIndex++
The CurAnimIndex is an int32 and has the value 2147483647 (max int). I would expect it to enter the branch since the value of CurAnimIndex after the increment should be a negative number
2147483647 is a positive number. Why would you expect that incrementing a positive number would yield a negative one? That doesn't happen in normal arithmetic. The compiler knows this and optimises according to that knowledge. If the initial value of CurAnimIndex
has been proven to be at least -1, then the check CurAnimIndex < 0
is known always to be false and can be optimised away.
Maybe your expectation is related to the fact that the operation overflows the maximum representable value. That expectation is misplaced because signed overflow isn't guaranteed to have such behaviour. In fact, signed overflow isn't guaranteed to have any particular behaviour. The behaviour of the program is undefined.
A correct way to do this is to first check whether the number is equal to maximum representable value and only increment if it isn't.
User contributions licensed under CC BY-SA 3.0