Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are members of a structure allowed to be static ?

Tags:

c

structure

#include<stdio.h>
struct str 
{ 
   static int a ;
    int b ;
 } s ;
int main()
{
static int p , k ;
printf("%d %d",sizeof(p),sizeof(s));
getchar();
return 0;
}

above code is giving errors . But if I redefine the first member of the structure to 'int' rather than 'static int' then it runs fine . Why static members are not allowed in the structure and what is its significance ?

like image 875
SlashGeek Avatar asked Aug 08 '12 06:08

SlashGeek


1 Answers

There's simply no such feature in C language. And there's no meaningful conceptual framework for such feature in C.

You see, in C++ terms, there's only one relevant difference between a static member variable and an ordinary global variable: the scope in which its name is declared and the corresponding naming syntax. A global variable could be called a, while a static member of the class would be called SomeClass::a. Besides scoped naming, there are no other differences. (I deliberately ignore other C++-specific features, like access control, since they don't exist in C and this question is really about C.)

In C language a struct type does not introduce its own scope. There's no such naming syntax as SomeStruct::a in C language. For this reason there's simply no reason to have static members in structs. You can declare a global variable instead and achieve the same effect. Call your global variable str_a to convey the intent to "associate" it with struct str and just think of that variable as a pseudo-static member of struct str.

Formally speaking, one could do it the same way in C++, i.e. completely ignore this feature of C++ language and use global functions and variables instead of static function and variables inside classes. However, by doing that one would forsake all member access control features of C++. And these features are really worth having. C language has no access control features, meaning that in C one loses [almost] nothing.

like image 147
AnT Avatar answered Sep 28 '22 02:09

AnT