CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5

Thread: typedef struc

  1. #1
    Join Date
    May 2010
    Posts
    83

    Wink 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,

  2. #2
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    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.

  3. #3
    Join Date
    Jan 2004
    Location
    Düsseldorf, Germany
    Posts
    2,401

    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.

  4. #4
    Join Date
    May 2010
    Posts
    83

    Re: typedef struc

    ah, you two are right!
    It works if you have a terminating NULL entry:

    x[]={
    {123},
    {123},
    {123},
    {NULL}
    };

    Great - solved!

  5. #5
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    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
  •  





Click Here to Expand Forum to Full Width

Featured