0

I have the following code:

#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; } } 

In x64 debug it prints "OK!" but in x64 release it prints "BUG!?", is there a problem with my code or is the compiler doing something wrong here? How can I fix or workaround this issue?

8
  • Just making sure, do you have the hotfix for update 3 (assuming you are using MSVC 2015)? Commented Mar 23, 2017 at 22:54
  • I'm on update 2 currently, is this something fixed in update 3? Commented Mar 23, 2017 at 22:55
  • I am not too sure, I just thought it might be relevant. Commented Mar 23, 2017 at 22:56
  • Those types should probably be uint16_t, int16_t, and int32_t, right? Since signed int isn't guaranteed to be 32 bits? Commented Mar 23, 2017 at 22:56
  • x64 Release (all the default settings) with MSVC 2015 Update 3 seems to give OK. Commented Mar 23, 2017 at 23:00

1 Answer 1

4

Since the value -63 triggers undefined behavior (sampleBits will be 0 thus you will be shifting -2 places) anything can happen:)

Sign up to request clarification or add additional context in comments.

1 Comment

Added a check so the shift value is limited to 0 and both now produce the correct value

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.