Reputation: 183
I have defined a struct like this
Struct rectangle{
int x;
int y;
int z;
};
and then in my main method, i will be assigning the variables:
void main(int argc, const char *argv[])
{
for(i=0;i<20;i++)
{
rectangle[i].x = 20;
rectangle[i].y = 10;
}
}
But I wont be assigning the 'z' variable of the struct anytime. Am i allowed to do this? hope i am not asking something very dumb!!
Thanks in advance!
Upvotes: 1
Views: 778
Reputation: 6227
Yes you can get away without declaring z
but the value for z will be undefined.
Think about using a default constructor for the struct and also defining rectangle z
as a gloabal or static will initialize it to 0
so you don't have to worry about the value it will take on otherwise.
Upvotes: 0
Reputation: 444
As said before, it won't harm. You can even print rectangle[i].z's value to see what was here before on the stack :).
Upvotes: 0
Reputation: 206646
You are allowed to do it. The member z
will have an indeterminate value though.
So If you use it, without assigning any value to it you will end up with an Undefined Behavior(UB).
However, If the structure object is an global or static object then z
will be implicitly initialized to 0
and you do not have to bother about UB.
Upvotes: 4
Reputation: 272802
Yes, that's fine. Any attempt to use rectangle[i].z
will result in undefined behaviour,* but that's not a problem so long as you don't try to use it.
rectangle
is declared as a global/static array, in which case all its members are implicitly initialized to zero.
Upvotes: 6