优化程序错误或未定义的行为?

时间:2017-03-23 22:52:24

标签: c++ visual-c++

我有以下代码:

#include <math.h>
#include <stdio.h>

using u16 = unsigned short int;
using s16 = signed short int;
using s32 = signed int;

s16 Algorithm(s16 sample)
{
    s32 absSample = static_cast<s32>(abs(sample));
    s32 sampleBits = absSample >> 7;
    s32 sampleMasked = absSample & 0x7F;

    s16 result = (u16)(sampleMasked << sampleBits)  | (u16)(1 << (sampleBits - 2));
    if (sample < 0)
    {
        result = -result;
    }
    return result;
}

int main() 
{
    s16 result = Algorithm(-63);
    if (result == -63)
    {
        printf("OK!\n");
        return 0;
    }
    else
    {
        printf("BUG!?\n");
        return 1;
    }
}

在x64调试中打印“OK!”但是在x64版本中它打印出“BUG!?”,我的代码是否有问题或者编译器在这里做错了什么?我该如何修复或解决此问题?

1 个答案:

答案 0 :(得分:4)

由于值-63触发未定义的行为(sampleBits将为0,因此您将移动-2个位置)任何事情都可能发生:)