What is the difference between a static and const variable?

前端 未结 17 1764
天命终不由人
天命终不由人 2020-11-29 18:39

Can someone explain the difference between a static and const variable?

17条回答
  •  爱一瞬间的悲伤
    2020-11-29 18:54

    Static Variables:

    • Initialized only once.
    • Static variables are for the class (not per object). i.e memory is allocated only once per class and every instance uses it. So if one object modifies its value then the modified value is visible to other objects as well. ( A simple thought.. To know the number of objects created for a class we can put a static variable and do ++ in constructor)
    • Value persists between different function calls

    Const Variables:

    • Const variables are a promise that you are not going to change its value anywhere in the program. If you do it, it will complain.

提交回复
热议问题