We are running a survey to help us improve the experience for all of our members. If you see the survey appear, please take the time to tell us about your experience if you can.
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
As far as I know, a construction like this is not allowed in C. Structures cannot have static members (you're probably thinking in C++, where classes can have static members).
You will need to define the static variable outside your structure.
"I have problem with struct."
Your problem seems to be in understanding how structures and the 'static' keyword work in 'C'!
Think about it: what sense does it make to have just one member of a structure as 'static'?!
What are you actually trying to achieve?
All instances of the structure would share one copy of the variable ?
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.
"All instances of the structure would share one copy of the variable ?"
How could that be?
Surely, structures are supposed to be contiguous? SO how could they share just one element?
That wasn't the question. The question was "What sense would it make?".
And as I said, it would make sense in certain contexts, and C++ allows this functionality in classes, but it is not allowed in a structure.
Hi friends,
Thank for suggestion, Actually, I am new to C and beginner of mcs-51 as well.
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.
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.