Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static variables in C structs [duplicate]

When I try to declare a struct with a static variable in it, the code doesn't get compiled and produces the error mentioned below

#include <stdio.h>

int main (){

struct test {
    int value;
    static int staticValue = 0;
}; 

return 0;
}

The error I get is;

 expected specifier-qualifier-list before ‘static’
  static int staticValue = 0;
  ^

Can anyone tell me what am I missing here?

like image 953
Rajith Gun Hewage Avatar asked Mar 17 '26 22:03

Rajith Gun Hewage


1 Answers

You might not want to declare your struct inside the main function -- that limits its scope to that of the function, which is seldom what you want.

Then, in C, static refers to object lifetime, and not to struct members. What you want is a static class member, which is a C++ (and not a C) construct.

like image 126
Marcus Müller Avatar answered Mar 20 '26 17:03

Marcus Müller



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!