Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why and when to use static structures in C programming?

Tags:

c

static

struct

I have seen static structure declarations quite often in a driver code I have been asked to modify.

I tried looking for information as to why structs are declared static and the motivation of doing so.

Can anyone of you please help me understand this?

like image 311
kutty Avatar asked Aug 31 '11 15:08

kutty


People also ask

Why do we use static in C?

A static function in C is a function that has a scope that is limited to its object file. This means that the static function is only visible in its object file. A function can be declared as static function by placing the static keyword before the function name.

What is static structure in C?

The static keyword in C has several effects, depending on the context it's applied to. when applied to a variable declared inside a function, the value of that variable will be preserved between function calls.

Why static is not used in structure?

Static variables should not be declared inside structure. The reason is C compiler requires the entire structure elements to be placed together (i.e.) memory allocation for structure members should be contiguous.

What is the main reason for using structure?

A structure is used to represent information about something more complicated than a single number, character, or boolean can do (and more complicated than an array of the above data types can do).


1 Answers

The static keyword in C has several effects, depending on the context it's applied to.

  • when applied to a variable declared inside a function, the value of that variable will be preserved between function calls.
  • when applied to a variable declared outside a function, or to a function, the visibility of that variable or function is limited to the "translation unit" it's declared in - ie the file itself. For variables this boils down to a kind of "locally visible global variable".

Both usages are pretty common in relatively low-level code like drivers.

The former, and the latter when applied to variables, allow functions to retain a notion of state between calls, which can be very useful, but this can also cause all kinds of nasty problems when the code is being used in any context where it is being used concurrently, either by multiple threads or by multiple callers. If you cannot guarantee that the code will strictly be called in sequence by one "user", you can pass a kind of "context" structure that's being maintained by the caller on each call.

The latter, applied to functions, allows a programmer to make the function invisible from outside of the module, and it MAY be somewhat faster with some compilers for certain architectures because the compiler knows it doesn't have to make the variable/function available outside the module - allowing the function to be inlined for example.

like image 94
fvu Avatar answered Sep 19 '22 17:09

fvu