I’ve seen the word static used in different places in C code; is this like a static function/class in C# (where the implementation is shared across objects)?
I’ve seen the word static used in different places in C code; is this
Share
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.
(1) is the more foreign topic if you’re a newbie, so here’s an example:
This prints:
This is useful for cases where a function needs to keep some state between invocations, and you don’t want to use global variables. Beware, however, this feature should be used very sparingly – it makes your code not thread-safe and harder to understand.
(2) Is used widely as an ‘access control’ feature. If you have a .c file implementing some functionality, it usually exposes only a few ‘public’ functions to users. The rest of its functions should be made
static, so that the user won’t be able to access them. This is encapsulation, a good practice.Quoting Wikipedia:
And to answer your second question, it’s not like in C#.
In C++, however,
staticis also used to define class attributes (shared between all objects of the same class) and methods. In C there are no classes, so this feature is irrelevant.