0

problem with static variable in c++

As we know, when a variable is declared as static, space for it gets allocated for the lifetime of the program. Then why it's giving error #include <iostream> using namespace std; int fun() { static int x = 10; return x; } int main() { x = 30; cout << x << endl; return 0; } Can I not modify static variable outside of the function where it has been declared?? If not then what is the means of static variable lifetime throughout the program??? Please help me anyone...............

28th May 2021, 2:23 PM
saurabh
saurabh - avatar
6 Respostas
+ 3
You are confusing variable lifetime with that of it's scope. The scope of a variable describes where in a program's text the variable may be used, while the extent (or lifetime) describes when in a program's execution a variable has a (meaningful) value Declaring a variable static will make its lifetime extend till the execution of program but still normal scope will apply here.
28th May 2021, 3:16 PM
Arsenic
Arsenic - avatar
+ 5
A static variable within a class is shared by all the objects of the class. A static variable inside a scope or function remains in the memory for the lifetime of the program. We should use a static variable whenever we want to reuse the modified value of the variable inside a function in the next function call. Or when we want all the objects to maintain a single copy of the class variable.
28th May 2021, 2:34 PM
JaScript
JaScript - avatar
+ 2
You can't modify it because the static local variable "n" has local scope, which means that it can be accessed, trough identifier "n", only in the function where it was defined.
28th May 2021, 3:16 PM
Lofty
Lofty - avatar
+ 1
@JaScript OK, But please take a look at it.... void print(){ static int n{0}; cout<<n<<endll n++; } int main(){ print(); print(); print(); ........... return 0; } Now please tell me if in every call if value of n is updated inside the function and prints according function...... Then why i can't use or modify the same 'n' outside of the function scope??????
28th May 2021, 3:02 PM
saurabh
saurabh - avatar
+ 1
Quanti thanks bro
28th May 2021, 3:19 PM
saurabh
saurabh - avatar
+ 1
Arsenic yup bro, You got my problem and also cleared.... Thanks a lot......
28th May 2021, 3:20 PM
saurabh
saurabh - avatar