This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

static inside struct

Hi,

I have problem with struct. Here is my code, please correct me.

   struct main_func
                {
                        static int kval;
                        int temp3;
                        char buf[8];
                }main_f;

If I do not put "static" to "int kval", everything OK, Anyone has idea?

Thanks,
pak

Parents
  • The concept isn't really all that bewildering (think static member variable of a class), it's just that C/C++ doesn't allow it for structures.

    C doesn't supports it at all, since it is specifically a C++ extension.

    C++ allows it for structures too. In C++, a struct and a class is basically the same thing in C++. The class defaults to protecting it's members, while a struct defaults to having evrything public.

Reply
  • The concept isn't really all that bewildering (think static member variable of a class), it's just that C/C++ doesn't allow it for structures.

    C doesn't supports it at all, since it is specifically a C++ extension.

    C++ allows it for structures too. In C++, a struct and a class is basically the same thing in C++. The class defaults to protecting it's members, while a struct defaults to having evrything public.

Children
  • Surely, structures are supposed to be contiguous? SO how could they share just one element?

    A struct or class must be continuous, but having a declaration (Assuming C++) like:

    struct/class X {
        static int a;
        int b;
        int c;
    };
    int X::a;
    

    just means that the variable a is within the X namespace.

    The actual struct/class will only contain the member variables b and c, and they will of course represent a continuous memory area.

    Since int X::a is a global variable in the X namespace, it must exist, even of no variables/objects of type X exists in the application.