Reputation: 53223
Is there any benefit to declare a local variable as "const" if I know that I won't be chaning its value?
Thanks,
Upvotes: 8
Views: 618
Reputation: 2992
Declaring the variable const will also allow the compiler to do optimisation - instead of say allocating an int on the stack and placing its value there, the compiler may just use the value directly with your code
ie The following:
const int test = 4;
DoSomething(test);
Could be compiled as
DoSomething(4);
by the compiler
Edit: Reply to "constant propagation" as the comments box has size limit
Using ildasm to check betweeen const and none const for release with optimisation:
The code
int test = 4;
Console.WriteLine(test*2);
Compiles to
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
// Code size 11 (0xb)
.maxstack 2
.locals init ([0] int32 test)
IL_0000: ldc.i4.4
IL_0001: stloc.0
IL_0002: ldloc.0
IL_0003: ldc.i4.2
IL_0004: mul
IL_0005: call void [mscorlib]System.Console::WriteLine(int32)
IL_000a: ret
} // end of method Program::Main
While
const int test = 4;
Console.WriteLine(test*2);
gets optimised to
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldc.i4.8
IL_0001: call void [mscorlib]System.Console::WriteLine(int32)
IL_0006: ret
} // end of method Program::Main
This is using 2010 in release with optimisations.
I did a search to learn more about constant propagation and while posible, the current compiler doesn't do this as mentioned here
Upvotes: 5
Reputation: 27495
I like to do this when I'm passing a boolean flag indicator to a method:
const bool includeFoo = true;
int result = bar.Compute(10, includeFoo);
This is more readable for me than a simple true/false, which requires reading the method declaration to determine the meaning.
Upvotes: 3
Reputation: 100248
Depending on case of use..
For example,
void Foo()
{
const string xpath = "//pattern/node";
new XmlDocument().SelectNodes(xpath);
}
in this case I think const declaration is meaningless
Upvotes: 0
Reputation: 6136
Further to the valid answers, not only do you tell the compiler that the value won't be changing, you quickly tell anyone else that will be looking at your code.
Upvotes: 1
Reputation: 7177
You would usually use a const throughout your entire solution. But the benefits for using in a local scope, would be that you know some place else in your scope you won't be changing it. And also if someone else is working on this code, they will know not to change it as well. This makes your program more maintainable, because you need to maintain only the const (even if its just in a local scope)
Upvotes: 6
Reputation: 27717
Declaring the local as const will let the compiler know you intention so you won't be able to change the value of your variable elsewhere in your function.
Upvotes: 2
Reputation:
Yes. You will protect your code from accidentally changing this variable.
Upvotes: 3