Reputation: 488
There are 2 common ways to convert positive number to negative and vice versa:
var a = -a;
and
var a = (-1)*a;
Second is preferred, as I know, but why? And is there any other best practice in converting the sign of the number (int, float, double, etc.) ?
EDIT: is there any difference in unary minus operation and multiplication to -1 ?
Upvotes: 0
Views: 2761
Reputation: 307
I don't understand why you think that the second would be the preferred method as the first one is a lot simpler and I use this method all the time. The second method is also a very common one but is not used as you would want to write the least amount of Code, but if you are planning to make everything clear... then I would prefer the Second method. You could also use Math.abs(x) if you wanted to but I would definitely prefer the first method. If you want to find out more about Math.abs, then you can find a lot of tutorials through google. Hope this resolved your question in a way. :)
Upvotes: 0
Reputation: 5764
On site http://tryroslyn.azurewebsites.net/ you can see code generated by compiler.
And for:
using System;
public class C {
public int M() {
int a = -2;
a = -a;
return a;
}
public int M1() {
int a = 3;
a = (-1) * a;
return a;
}
}
Compiler generates:
.class private auto ansi '<Module>'
{
} // end of class <Module>
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
// Methods
.method public hidebysig
instance int32 M () cil managed
{
// Method begins at RVA 0x2050
// Code size 4 (0x4)
.maxstack 8
IL_0000: ldc.i4.s -2
IL_0002: neg
IL_0003: ret
} // end of method C::M
.method public hidebysig
instance int32 M1 () cil managed
{
// Method begins at RVA 0x2058
// Code size 8 (0x8)
.maxstack 2
.locals init (
[0] int32
)
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: ldc.i4.m1
IL_0003: ldloc.0
IL_0004: mul
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ret
} // end of method C::M1
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
// Method begins at RVA 0x206c
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method C::.ctor
} // end of class C
As you see code for method M i much simplier and shorter.
Then -a
is better way.
Upvotes: 6