Reputation:
I have a question about the member variables of static struct in C language.
Someone said we can declare a static struct
, but in C, struct do not have the static members like class in C++, what does this mean? If I declare a static struct, what is the status of the members variable? can some one help me on this?
Upvotes: 7
Views: 23364
Reputation: 104718
I have a question about the member variables of static struct in C language.
Someone said we can declare a static struct
Correct/legal:
// (global scope)
static struct t_struct {
int a;
} THE_STATIC_VARIABLE;
but in C, struct do not have the static members like class in C++
// (global scope)
struct t_ill_struct {
static int a; // << ill-formed in C, but valid in C++
};
what does this mean? If I declare a static struct, what is the status of the members variable? can some one help me on this?
Using the above example, it means that THE_STATIC_VARIABLE
will have static storage. The following are equivalent:
A
// (global scope)
static struct t_struct {
int a;
} THE_STATIC_VARIABLE;
B
// (global scope)
struct t_struct {
int a;
};
static struct t_struct THE_STATIC_VARIABLE;
That is to say, every translation which sees THE_STATIC_VARIABLE
's definition will get its own copy.
If you want the same effect as a static C++ member, you will have to declare it in another scope -- outside of a struct's declaration:
// file.h
// (global scope)
struct t_struct {
int a;
};
extern struct t_struct THE_GLOBAL_VARIABLE;
// file.c
struct t_struct THE_GLOBAL_VARIABLE;
Now we really have exactly one, like in C++.
Upvotes: 4
Reputation: 215350
static
in C means:
In C++, there is also one additional meaning:
Upvotes: 4
Reputation:
Note that a static struct itself is different from a static member of a struct. While you can declare a static struct variable:
static struct MyStruct s;
you can't define a struct type with a static member:
struct MyStruct {
static int i; // <- compiler error
};
The reason for this is that in C, a struct is a type - declaring a type of which a member variable is always the same instance (i. e. static) for multiple instances of that type is simply nonsense. In C++, structs are in reality classes (they only differ in the default visibility scope of members), and in C++ the static keyword means something else in this case. It means a class method - but since C doesn't have classes and methods, this doesn't make sense and is invalid in C.
Lesson learned: C++ is not C.
Upvotes: 9