+ 2

I have a doubt about static variable

#include<stdio.h> #include<conio.h> void function(); void function(){ static int a=10; printf("%d",a); } int fun(); int fun(){ printf("\n%d",a); return 0; } void main(){ function(); fun(); getch(); } According to static variable it does not lose its value even after function ends but here the compiler is generating a error and that is "undefined symbol a" But a is a static variable so it should retains its value in the other function as well Please explain me

14th Oct 2024, 3:36 PM
Rishi Prajapati
Rishi Prajapati - avatar
3 Antworten
+ 6
It retains value during function calls but, in the above code you are accessing the 'a (variable)' in another function that is out of scope, the 'static int a ' variable scope is inside the function() only. To run the above code successfully, declare the 'a' as a global variable. #include<stdio.h> #include<conio.h> static int a = 10; void function(); void function() { printf("%d",a); } int fun(); int fun() { printf("\n%d",a); return 0; } void main() { function(); fun(); getch(); } The variable 'a' is declared a global variable so it can be accessible by all functions and retain its value. So the error is because the variable is not visible to the fun()
14th Oct 2024, 4:14 PM
Praveen Kumar Patini
Praveen Kumar Patini - avatar
+ 5
Static means the variable is only created and assigned once on the scope it is in. It does not automatically make it globally available. You declared it inside a function, so it is static within the function. But it will not be visible outside the function. Praveen Kumar Patini is right. Maybe you are confusing it with global variables. Then you should declare it on main or outside of it. Here is what happens when you declare variable x static inside a function (foo1). Compare it with how a non-static variable x behaves in foo2. Static x keeps a static reference to it's value when foo1 is recursively called while non-static x is re-initialized with every call in foo2. So foo1 x will decrement properly while foo2 x keeps getting set to 5. Static did not make foo1 x global, it just prevents it from getting re-initialized. Note how the two x are invisible to each other. That is because they are available only within each function's scope. https://sololearn.com/compiler-playground/c4C2IiRIm1mg/?ref=app
15th Oct 2024, 12:56 AM
Bob_Li
Bob_Li - avatar
+ 3
Thank you Bob_Li Now I understood properly
15th Oct 2024, 3:34 PM
Rishi Prajapati
Rishi Prajapati - avatar