Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there an extra operation when using the negative number shorthand in C#?

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)?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading