Go Down

Topic: Why does "for" not work (Read 1 time) previous topic - next topic

dilbert98122

If you mean doing this:
Code: [Select]
for( int i=0, int voltageraw=0 ; i<20; i++)
{
   // stuff
}

// voltageraw no longer exists here

Then voltageraw will only exist inside the for loop because you're declaring it inside the loop.  You probably want to use the value after the for loop is done though.

But this should work:
Code: [Select]

int voltageraw;

for( int i = 0, voltageraw = 0; i<20; i++)
{
// stuff
}

// i no longer exists, but voltageraw does


Because voltageraw is declared before teh for loop, it continues to exist after the loop.

dilbert98122

Er, my bad...  I don't think the second example would work as expected either.  I think it would create a second voltageraw that would only exist in the for loop, and outside of the loop, you'd be accessing the original voltageraw (which was not changed during the loop).

This is why I always consider it best practice to declare my variables at the beginning of my function rather than later in the code, so that they're all declared in an easy to find spot and I don't get tripped up on scoping rules.

This will work:
Code: [Select]

int i, voltageraw;

for( i=0, voltageraw=0 ; i<20; i++)
{
   // stuff
}


KenH

Thank you Dilbert - I'm studying your statements and trying to understand.  Allow me time to run the code thru a breadboard setup - that always helps me understand.  I had never really understood what that section of code did other than "smoothed" (averaged) analog input readings.  Now I am starting to understand more what is actually going on.

Ya'll are my only teachers here other than all the reading/coding I'm doing, and I sure do appreciate the help.  Thank you.

Ken H>

Go Up