The difference between static and constant variables

What is the difference between "static" and "const" when it comes to declaring global variables,

namespace General { public static class Globals { public const double GMinimum = 1e-1; public const double GMaximum = 1e+1; } } 

which is better (given that these variables will never change)

 namespace General { public static class Globals { public static double GMinimum1 = 1e-1; public static double GMaximum1 = 1e+1; } } 
+5
source share
3 answers

const and read-only perform a similar function for data members, but they have several important differences. The constant member is determined at compile time and cannot be changed at run time. Constants are declared as a field using the const keyword and must be initialized as they are declared.

The static modifier is used to declare a static member, which means that the element is no longer bound to a specific object. The value belongs to the class, in addition, the member can be accessed without instantiating the class. There is only one copy of static fields and events, and static methods and properties can only access static fields and static events.

+8
source

const variables cannot be changed during compilation time. They are good for things that are really persistent (i.e. pi)

static members are shared memory that is accessible to all instances of a particular class and more if access modifiers are used, as a public (they can feel like global variables in programming languages โ€‹โ€‹like JavaScript). Static members behave like regular variables that can be reassigned each time.

In your case, if the numbers are guaranteed never to change, then make them const. If they change, you will have to recompile the program with the new value.


Which one is better? if you use const , then literal values โ€‹โ€‹become baked in the assembly and provide improved performance.

If the values โ€‹โ€‹ever need to be changed, then the time taken to change the source and recompile quickly destroys this marginal increase in performance.

+4
source

const is a constant value and cannot be changed. It is compiled into an assembly.

static means that this value is not associated with the instance, and it can be changed at runtime (since it is not readonly ).

So, if the values โ€‹โ€‹never change, use constants.

+2
source

All Articles