Consider the following c++ code:
int main()
{
int a = -3 >> 1;
int b = -3 / 2;
cout << "a = " << a << ", b = " << b << endl;
return 0;
}
When executed, this code give this result:
a = -2, b = -1
I'm a little puzzled, because I thought that these 2 operations produced the same code in the compiled exe, i.e. something like:
shr ax, 1
But it seems that it's not the case (I tested with 2 different compilers). Somebody can explain to me why these operations doesn't produce the same result?
---- EDIT ON the 17.02.2018 ----
Well, I know this is a newbie question, even if I'm not really a beginner in C++
In fact, I understand perfectly what happen in binary when I apply a shift right (i.e. shr or >> operator) on a value. This was not my question.
Rather, my question was about the difference between applying a binary shift on a value or make a division on a value. I expected that the result was the same, because until now I assumed that the compiler replaced a division by 2, or a multiplication by 2, by the appropriate shr/shl instruction during the compilation, as an optimization. Assuming that, the produced binary should be the same for the both instructions, so the result should also be the same.
But it is apparently not the case. For that reason, I would be happy to know what happen under the hood while the compiler compiles these both instruction (analyzing a mnemonic is not really my strong point), what are their differences, and finally, this should let me understand why the result differs in mathematical terms.
As a concrete case, I faced this issue in a source code for a graphical application I tried to make simpler. To facilitate the human reading of the code, I replaced some code like "(widthB - widthA) >> 1" by "(widthB - widthA) / 2". But doing that introduced a bug: several graphic items were no longer centered as expected. From that I noticed that replacing the shifting by a division produced different result if the value to divide was negative, it's the reason of the above question.
I hope this will clear up the situation.