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)?
C – What Does ‘static’ Mean?
c++staticsyntax
c++staticsyntax
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)?
Best Answer
(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,
static
is 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.