hi,
why cant we initialise structure variables at the time structure declaration.
Code:struct { int i=10; char a='s'; };
hi,
why cant we initialise structure variables at the time structure declaration.
Code:struct { int i=10; char a='s'; };
Exactly what I was going to say.
If you want to do that kind of thing, you want to be using C++, in which you can use "constructors" to achieve the desired effect.
My homepage
Advice: Take only as directed - If symptoms persist, please see your debugger
Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"
And constructors can be "faked" in C.
So.... yeah....Code:struct something { int x; }; ... struct something * create_something(int x) { struct something *s = malloc(sizeof(*s)); s->x = x; return s; }
Code:struct { int i; char a; } instance = { 10, 's' }; int main() { printf ("%d %c\n", instance.i, instance.a); return 0; }
Yes, on a per instance basic. Not default values, though, like the OP appears to want.
Think of it this way:
Structures are blueprints on how to build your custom data type. The thing is that it's a blueprint - it doesn't contain information about what the actual objects created from it contains. So you can't modify the blueprint to hold information.
Instead, you must first CREATE your object FROM the blueprint and initialize it, which is what robwhit just did.
thank you for info.i was getting doubt on it. now iam able to understand.
You are right that is new + constructor. I put fake in quotation marks because I didn't think it was the right word, but it still fit the idea. It's not a constructor, but it can be thought of as one.
Also, I believe C++ really does use these kind of techniques, though, under the hood more or less. So the word fake becomes less appropriate if that is the case.