-
typedef struc
hi,
i have the following piece of code,
isn't the for loop supposed to loop while a x[i].x is present (->true)?
Cause it doesn't stop when there`s no x[] left....
typedef struct x{
int y;
}x;
x[]={
{123},
{123},
{123},
};
for (int i=0; x[i].x;i++){
//do stuff
}
I am sure, thoguh, i`ve seen this before and it worked.
thx,
-
Re: typedef struc
That will loop as long as the value of x[i].x is non-zero. Since you have no idea what values happen to be in memory beyond the end of the array, the value of x[i].x for any i >= 3 is undefined.
-
Re: typedef struc
This will not loop at all. It would have to compile first before looping.
-
Re: typedef struc
ah, you two are right!
It works if you have a terminating NULL entry:
x[]={
{123},
{123},
{123},
{NULL}
};
Great - solved! :)
-
Re: typedef struc
That's one approach, yes. The "terminating NULL" is commonly used in C code, most notably with C-style strings.
In C++, it's better practice to just keep track of the array size (or use a container such as std::vector which tracks the array size for you!) and only loop that far, eg,
Code:
int xsize = 3;
for (int i=0; i < xsize;i++){
//do stuff to x[i]
}