-
June 1st, 2010, 08:18 AM
#1
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,
-
June 1st, 2010, 08:20 AM
#2
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.
-
June 1st, 2010, 08:40 AM
#3
Re: typedef struc
This will not loop at all. It would have to compile first before looping.
More computing sins are committed in the name of efficiency (without necessarily achieving it) than for any other single reason - including blind stupidity. --W.A.Wulf
Premature optimization is the root of all evil --Donald E. Knuth
Please read Information on posting before posting, especially the info on using [code] tags.
-
June 1st, 2010, 08:46 AM
#4
Re: typedef struc
ah, you two are right!
It works if you have a terminating NULL entry:
x[]={
{123},
{123},
{123},
{NULL}
};
Great - solved!
-
June 1st, 2010, 09:40 AM
#5
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]
}
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|