Why can't we declare a static variable within a structure in the C programming language?
Why ca开发者_Go百科n't we declare a static variable within a structure in the C programming language?
In C++, a struct is basically a class with all members public, so a static variable makes good sense there.
In C, a struct is a contiguous chunk of memory with fields. A static variable can not be created without changing that (as to implement a static you need to refer to a single memory location from all structs of that type), and that would be a big difference in complexity without much benefit.
Because C is not C++.
Because the C standard does not permit it.
Because it has no meaningful interpretation in C.
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. It is possible to declare structure inside the function (stack segment) or allocate memory dynamically(heap segment) or it can be even global (BSS or data segment). Whatever might be the case, all structure members should reside in the same memory segment because the value for the structure element is fetched by counting the offset of the element from the beginning address of the structure. Separating out one member alone to data segment defeats the purpose of static variable.
It is possible to have an entire structure as static.
reference : https://en.wikipedia.org/wiki/Static_(keyword)
Because in c we can't access static variable with stucture name. In c++ we can access static member variable with class name,like below.
ClassName::staticVariableName
'C' stucture don't provide such facility.
精彩评论