Compiler optimization does typecast incorrectly - by jmurray_aerotech

Status : 

  Fixed<br /><br />
		This item has been fixed in the current or upcoming version of this product.<br /><br />
		A more detailed explanation for the resolution of this particular item may have been provided in the comments section.

Sign in
to vote
ID 524796 Comments
Status Closed Workarounds
Type Bug Repros 0
Opened 1/13/2010 12:24:39 PM
Access Restriction Public


When compiler optimization is set to "Full Optimization", I have come up with a reproducable case where the optimized code does a typecast incorrectly.  Casting a double to an unsigned long to an unsigned short will incorrectly result in the value 0 if the uppermost bit of the unsigned long is 1.  Turning off optimization causes the compiled code to work as expected.  Here is the code:

#include <stdio.h>
#include <conio.h>

void functionCall(double dData);

int main() {

	// Test 1: this works correctly
	//   wValue = 0xBEEF (correct)
	// Test 2: Demonstrates the compiler optimizing correctly
	// The following project setting determines the behavior
	// Project Properties -> Configuration Properties -> C/C++ -> Optimization -> Optimization
	//   "Full Optimization /Ox" -> wValue = 0x0 (incorrect)
	//   "Disabled /Od" -> wValue = 0xBEEF (correct)
	return 0;

void functionCall(double dData) {
	unsigned short wValue;
	wValue = (unsigned short)((unsigned long)dData & 0xFFFF);
	printf("\tdData: %lf\n", dData);
	printf("\t(unsigned long)dData: 0x%X\n", (unsigned long)dData);
	printf("\twValue: 0x%X\n\n", wValue);
Sign in to post a comment.
Posted by Microsoft on 3/23/2010 at 11:28 AM
Sorry for the delay. I've tested this locally, and I'm seeing the issue you are reporting. Nice repro. :)

Unfortunately, regardless of how complicated the fix is, the fix will not make it into Visual Studio 2010, as this bug does not meet the bar for VS2010 this late in the product cycle. However, we will look into including the fix in the next version of Visual Studio.

Let me know if you need any help to work around this bug in your code.

Posted by Microsoft on 1/13/2010 at 9:44 PM
Thanks for your feedback.

We are rerouting this issue to the appropriate group within the Visual Studio Product Team for triage and resolution. These specialized experts will follow-up with your issue.

Thank you