The following code generates different results under debug mode and release mode (using Visual Studio 2008):
int _tmain(int argc, _TCHAR* argv[])
{
for( int i = 0; i < 17; i++ )
{
int result = i * 16;
if( result > 255 )
{
result = 255;
}
printf("i:%2d, result = %3d\n", i, result) ;
}
return 0;
}
The output of debug mode, which is as expected:
i: 0, result = 0
i: 1, result = 16
(...)
i:14, result = 224
i:15, result = 240
i:16, result = 255
The output of release mode, where i:15 result is not correct:
i: 0, result = 0
i: 1, result = 16
(...)
i:14, result = 224
i:15, result = 255
i:16, result = 255
By choosing "Optimization -> Not to optimize" in Visual Studio under release mode, the output result will be correct. However I would like to know why the optimization process could lead to erroneous output.
Update:
As suggested by Mohit JainBy, prints by:
printf("i:%2d, result = %3d, i*16=%d\n", i, result, i*16) ;
The release mode output is correct:
i: 0, result = 0, i*16=0
i: 1, result = 16, i*16=16
(...)
i:14, result = 224, i*16=224
i:15, result = 240, i*16=240
i:16, result = 255, i*16=256