struct temp{
const int i;
};
How do i initialize my variable 'i' inside the main() function?
You cannot assign anything to a constant object. A constant object can only be initialized at the point of declaration, as in
struct temp t = { 5 };
I.e. you get only one chance. If you missed your chance to initialize a constant object, you are out of luck - the object will remain uninitialized forever.
For this reason it is generally not a good idea to create constant fields inside generally non-constant struct objects, unless you really know what you are doing.
That's the theory of it.
In practice you might sometimes see people resort to various "hacks" and simply ignore the constness of the field. For example, the whole struct can be "assigned to" by using memcpy
. In some situations in C language you have no choice by to do something like that (with malloc
ed objects, for example, since C language provides no means for supplying initializers in such contexts).
Again, C language is not very well suited to handling such types, which is why they should be used only in a very well planned contexts.
You can do it in the struct initialiser, e.g.
int main()
{
struct temp tester = { .i = 5 };
}