for loop index variable

Discussion in 'C++' started by Guest, Jul 19, 2005.

  1. Guest

    Guest Guest

    (I tried to post this earlier, but it seems without success)

    A similar question to this has been answered many times, to whit the
    question applying when the index variable of a for loop is declared in
    the loop header, but this time that isn't the case:

    I've got a piece of code a bit like this:

    #include <iostream>
    #include <cmath>

    for (x=0; x<digits; x++)
    {
    //do something dependent on the value of x
    }

    //Depending on the value of x after one of these
    //loops, I cd do the last step better outside the loop?

    What is the value of x when the loop terminates? Is it indeed digits,
    as one would expect? Does it reset to 0? Could it be anything
    depending on my implementation?

    Thanks,

    James M.
     
    Guest, Jul 19, 2005
    #1
    1. Advertisements

  2. A for loop is not "magical". It has three sections: initialization,
    condition, expression. The initializaition is done once before the loop
    begins, the condition is checked at each loop (including before the
    first one) and the expression is evaluated after the first loop and in
    subsequent loops.

    Whatever you write in these sections is what happens. If you write

    for (x=0; x<digits; ++x)
    {
    }

    it's the same thing as

    x=0;
    for(;;)
    {
    if (x>=digits)
    break;

    ++x;
    }

    So when the loop ends (if it does), you are assured that x>=digits.


    Jonathan
     
    Jonathan Mcdougall, Jul 19, 2005
    #2
    1. Advertisements

  3. Guest

    John Carson Guest

    You don't show the declaration of x. If your code is really:

    int x;

    for (x=0; x<digits; x++)
    {
    //do something dependent on the value of x
    }

    then x will equal digits immediately after the loop (there is no resetting
    to zero) --- assuming that there is no break; or goto; statement inside the
    loop that could terminate it prematurely and no code inside the loop that
    alters the value of x (e.g., x = digits +10;).
     
    John Carson, Jul 19, 2005
    #3
  4. Guest

    Peter Julian Guest

    It depends where x was declared, something you failed to show in your
    example.

    Assuming that int x; was indeed declared outside the loop, x will hold
    whatever value the conditional expression "failed" with (x<digits).
    So x == digits following the loop if x++ is its only modifier.

    The key here is scope, where was x declared?
     
    Peter Julian, Jul 19, 2005
    #4
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.