LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   [C] for looping problem (https://www.linuxquestions.org/questions/programming-9/%5Bc%5D-for-looping-problem-105827/)

wuck 10-19-2003 05:43 AM

[C] for looping problem
 
I'm almost sure to be right about the following:

If you've got two variables, x and argc, (used for command-line input) and you want to make a loop where x will constantly be raised by one, started with value 1, until the value of argc is reached.
To me, the most neat approach to do that is by using for:

Code:

for ( x = 1 ; x == argc ; x++ )
{

 ( ... )

}

Now I just can't believe my eyes, because on my box, this does not work. All code (the ( ... ) ) simply won't be executed. The only way to get this working, is the following:

Code:

int main(int argc, char **argv)
{
        int x;

        if (argc == 1)
                PrintUsage ();
        else
                for ( x = 1 ; ; x++ )
                {
                        if (x == argc)
                                break;

                        printf ("%i %s\n", x, argv[x]);

                }



        Head ();
        Body ();
        Tail ();
}

:confused: Have I overlooked something?The above example _does_ work, but the first should, too! Right?

SaTaN 10-19-2003 06:07 AM

Re: [C] for looping problem
 
This is the miskate you are making
Code:

for ( x = 1 ; x <= argc ; x++ )
//You used x==argc
{
 ( ... )
}

The for loop should continue until the value of argc has been reached n so the condition should be x<=argc and not x==argc

wuck 10-19-2003 10:05 AM

So:

Code:

for ( x = 1 ; !(x == argc) ; x++)
Should work, too?

Hko 10-19-2003 10:10 AM

Sure, as well as:
Code:

for (x = 1; x != argc; x++)
though, aesthetically, SaTaN's code is the best of the three.

wuck 10-19-2003 10:38 AM

Thank you both.

Kurt M. Weber 10-19-2003 11:44 AM

Well, they're not quite the same.

Satan's will execute the loop so long as x is less than or equal to argc, while the other two examples will only execute when x is not equal to argc (meaning that when x is equal to argc, the loop will terminate before it goes through).

Hko 10-19-2003 04:29 PM

True, but that only makes satan's code the better o the three. Because x is incremented by 1 the result in this case is the same.


All times are GMT -5. The time now is 06:42 AM.