-2

We all know the difference between static and const. Can someone help me understand all the similarities?

Trevor
  • 7,777
  • 6
  • 31
  • 50
Mohammad Rayan
  • 312
  • 3
  • 11

1 Answers1

1

The only "similarity" to speak of, would be that const is implicitly static and thus can not be explicitly marked as such.

Memory wise const is slightly more effective then static, as it skips any need for a pointer. A static still exist as a value in memory, that can be read and (at least theoretically) written. Everytime the static variable is used, a pointer to that one instance will be placed and resolved at runtime.

Meanwhile consts are just a raw value, de-facto hardcoded. Every use of a const, is the same as writing it's literal value. This is beneifical on primitives (as a value is cheaper then a pointer + a value).

I am not 100% sure about the const implementation on class references. I would guess it actually behaves more like a readonly static in that case.

In practice you run into more readonly statics then constants. For example, all the semi-constant fields on the Path class are readonly static. Constants (unless we talk about Enums) have very little value at runtime or for other code that is accessing your stuff.

Trevor
  • 7,777
  • 6
  • 31
  • 50
Christopher
  • 9,634
  • 2
  • 17
  • 31