C++ 优化器错误或未定义的行为?

C++ 优化器错误或未定义的行为?,c++,visual-c++,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 =

我有以下代码:

#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;
    }
}
#包括
#包括
使用u16=无符号短整数;
使用s16=有符号短int;
使用s32=有符号整数;
s16算法(s16样本)
{
s32 abs样本=静态_铸造(abs(样本));
s32采样位=absSample>>7;
s32 sampleMasked=absSample&0x7F;

s16结果=(u16)(样本屏蔽因为值
-63
触发未定义行为(
样本位
将为0,因此您将移动-2位)任何情况都可能发生:)

因为值
-63
触发未定义行为(
样本位
将为0,因此您将移动-2位)任何事情都可能发生:)

请确保您有更新3的修补程序(假设您使用的是MSVC 2015)?我目前正在更新2,这在更新3中是固定的吗?我不太确定,我只是认为它可能是相关的。这些类型应该是
uint16\u t
int16\u t
,和
int32\u t
,对吗?因为
signed int
不能保证为32位?x64版本(所有默认设置)MSVC 2015更新3似乎给出了
OK
。请确保,您有更新3的修补程序(假设您使用的是MSVC 2015)?我目前正在更新2,这在更新3中是固定的吗?我不太确定,我只是认为它可能是相关的。这些类型应该是
uint16\u t
int16\u t
,和
int32\u t
,对吗?因为
signed int
不能保证为32位?x64版本(所有默认设置)MSVC 2015更新3似乎给出了
OK
。添加了一个检查,使移位值限制为0,现在两者都产生了正确的值添加了一个检查,使移位值限制为0,现在两者都产生了正确的值