what is the difference between static and normal v

2020-07-23 06:23发布

I need to know the difference,am beginner.

标签: c++
9条回答
Melony?
2楼-- · 2020-07-23 07:11

Main difference in static and normal variable is in their lifetime, for example scope and lifetime of local variable is within the function-loop in which it is declared, but scope of static variable is same as local variable means it will be accessed within which function it is declared(if not defined globally), but lifetime is through the program. So memory allocation depends on the lifetime, so as static variable will not die till program terminates so no new memory allocated, so fixed memory address allocated to static variables and value in that address will be overwritten every time we change the value of variable, while for normal variable as soon as you will go out of scope, variable will die(means memory will be freed for that variable) and when you will define variable again new memory address will be assigned, new value will be stored in address and no concept of overwrite(when we go out of scope).

查看更多
Luminary・发光体
3楼-- · 2020-07-23 07:11

Apart from differences in all these answers, there is one more difference between static and local variables:

local variables are stored on the stack, while static variables are stored in the data section of a process memory.

查看更多
Bombasti
4楼-- · 2020-07-23 07:21

A static variable is a single memory location associated with the class.

A non-static variable (that is a member of a class) represents a different memory location for each instance of the class.

Static variables can be initialized only once and assign to 0 when an object is created.

查看更多
登录 后发表回答