what is better to use while or for

This is a discussion on what is better to use while or for within the C Programming forums, part of the General Programming Boards category; hello ,... im reading smser (smser.sf.net)project i added few docs and i thought going tru the code and maybe i ...

  1. #1
    Registered User
    Join Date
    Apr 2007
    Posts
    112

    what is better to use while or for

    hello ,...

    im reading smser (smser.sf.net)project i added few docs and i thought going tru the code and maybe i could help the orihnal programer (i actualy thound few things that could make the program better but still ... )

    in the code there is a
    Code:
    while (fgets(s,MAXLINELENGTH,f)!=NULL)
        	{
        	//handle line of file
        	strcpy(&a[i* MAXNUMLENGTH],s);
            i++;
        	}

    im thinking that it will be better to do :
    Code:
    for (i = 0 ; fgets(s,MAXLINELENGTH,f)!=NULL ; i++ ) 
    {
        strcpy(&a[i* MAXNUMLENGTH],s);
    }
    why Gaos didn't had a wife ?
    http://bsh83.blogspot.com

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Either is really quite acceptable. Some people frown at using a condition in a for-loop that is completely unrelated to the variable in the iteration itself. But that's one of those things that can be debated either way. Modern compilers will probably generate identical code for both choices.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  3. #3
    Registered User
    Join Date
    Oct 2001
    Posts
    2,129
    to make them identical:
    Code:
            i = 0;
            while (fgets(s,MAXLINELENGTH,f)!=NULL)
            {
            //handle line of file
            strcpy(&a[i* MAXNUMLENGTH],s);
            i++;
            }
    or
    Code:
    for (; fgets(s,MAXLINELENGTH,f)!=NULL ; i++ ) 
    {
        strcpy(&a[i* MAXNUMLENGTH],s);
    }

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21