In C# one can make a positive int negative using the minus sign - like so:
var positiveInt = 5;
var negativeInt = -positiveInt;
Is there an extra operation taking place under the hood when doing this (i.e. is the CPU actually multiplying the number by -1)?
>Solution :
You can use SharpLab or the Godbolt Compiler Explorer to see what the .NET JIT compiler emits for various pieces of code. In particular, it’s instructive to compare the following two methods:
static int M1()
{
var positiveInt = 5;
var negativeInt = -positiveInt;
return negativeInt;
}
static int M2(int positiveInt)
{
var negativeInt = -positiveInt;
return negativeInt;
}
For M1, the JIT compiler performs constant propagation and emits code that simply returns 0xfffffffb, representing the constant -5:
mov eax, 0xfffffffb
ret
But for M2, where the positiveInt argument in register ecx is an unknown value, the JIT compiler emits a neg instruction (for x86) that negates the value:
mov eax, ecx
neg eax
ret