22

Is it legal to have a "static" member within a C struct?

For example

struct my_struct {
    int x;
    static int y;
};

If indeed it is legal,then what are the implications of the usage of the "static" keyword?

Mateusz Piotrowski
  • 8,029
  • 10
  • 53
  • 79
Mno
  • 281
  • 1
  • 2
  • 7

6 Answers6

19

No, that would make no sense in C. It's valid in C++ though.

Paul R
  • 208,748
  • 37
  • 389
  • 560
7

No, not in C

(You can have a static member in a C++ structure.)

Mitch Wheat
  • 295,962
  • 43
  • 465
  • 541
4

You're probably getting confused by the fact that Static isn't used for the same purposes that it is in languages such as Java or C# (or C++ for that matter). This post explains C's usage of static thoroughly:

What does "static" mean?

Community
  • 1
  • 1
Snukus
  • 1,302
  • 9
  • 17
2

It seems like you're asking about the intuition behind a static member. A static member means one-per-type instead of one-per-instance. In your case, if you had

struct my_struct a, b;

then a and b would each have their own x but would share a common y. This is also true of static member functions.

But like was stated, this doesn't apply to C. It does to C++ and Java, though.

Adam
  • 16,808
  • 7
  • 52
  • 98
-2

you cannot use the static specifier in a structure...

structure variables cannot be initialized inside a structure and static specifier initializes the variable to 0..

this behavior is not allowed in C..

Raghu Srikanth Reddy
  • 2,703
  • 33
  • 29
  • 42
-2

On compilation Compiler throw error; Because whenever compiler come across static keyword, its expected to generate code to initialize (zero or explicitly specified value) the static variable in data segment or BSS segment. In our scenario memory will not be allocated for a structure declaration, and so compiler throws error.