Is there a difference between declaring a static variable outside of a function and declaring a static variable inside a function?
Also, what’s the difference between declaring a variable as static and just declaring an extern variable?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The difference is that the static variable inside the function is visible inside the function only, whereas the static variable outside may be seen by any function from its point of declaration to the end of the translation unit.
Otherwise, they behave the same.
Declaring a variable outside of a function without the keyword
staticmeans it is visible (accessible) outside the file (translation unit) where it is defined (as well as from the point of definition to the end of the translation unit). If you declare a variable asextern, it means that there is a definition somewhere else – possibly in the same translation unit, but more likely in another. Note that it is possible to declare an extern variable inside a function, but it can only be defined outside of a function.