We all know the difference between static and const. Can someone help me understand all the similarities?
-
I had read this before posting my question. It only states the difference and not similarities. – Mohammad Rayan Dec 25 '19 at 04:10
-
So, everything *except differences* is *similarities*? – Tân Dec 25 '19 at 04:13
-
1What information are you looking for exactly? – ProgrammingLlama Dec 25 '19 at 04:34
1 Answers
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.

- 7,777
- 6
- 31
- 50

- 9,634
- 2
- 17
- 31