Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
361 views
in Technique[技术] by (71.8m points)

c - Are members of a structure allowed to be static ?

#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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...