Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring a local variable as const

Tags:

c#

constants

Clearly, declaring a local variable as const, prevents runtime modification. Const instance variables are static (I believe). Does this have any bearing on the nature and use of const local variables? (e.g. threading)

like image 723
Ben Aston Avatar asked Jun 29 '10 13:06

Ben Aston


People also ask

How can we declare a local variable as constant?

Variables can be declared as constants by using the “const” keyword before the datatype of the variable. The constant variables can be initialized once only. The default value of constant variables are zero.

Should I use const on local variables?

Yes, you should use const whenever possible. It makes a contract that your code will not change something. Remember, a non-const variable can be passed in to a function that accepts a const parameter.

Can you declare local variables?

Declaring Local VariablesYou can declare them at the start of the program, within the main method, inside classes, and inside methods or functions. Depending on where they are defined, other parts of your code may or may not be able to access them. A local variable is one that is declared within a method.

How do you declare const?

You use the Const statement to declare a constant and set its value. By declaring a constant, you assign a meaningful name to a value. Once a constant is declared, it cannot be modified or assigned a new value. You declare a constant within a procedure or in the declarations section of a module, class, or structure.


1 Answers

"const" variables have to have a primitive type (e.g. int, bool). Whenever a "const" variable appears in the source code (whether it's local or global), this instance is replaced with the const value itself. So:

const int foo = 42;
return foo + 69;

after optimizing becomes:

return 42 + 69

or rather:

return 111;

There are no threading issues because const variables have primitive types and they only exist at compile time.

like image 98
sthalik Avatar answered Sep 24 '22 04:09

sthalik