|
|
View previous topic :: View next topic |
Author |
Message |
JAM2014
Joined: 24 Apr 2014 Posts: 138
|
For loop query.... |
Posted: Thu Apr 20, 2017 1:17 pm |
|
|
Hi All,
Can I use a For loop to sequence 0 (zero) to 255 (inclusive) with an int8 variable?
This gives me an endless loop:
Code: |
for ( iIndex = 0 ; iIndex <= 255 ; iIndex++ )
{
fprintf(Console, "Index: %u\n\r", iIndex);
delay_ms(50);
}
|
I tried using ++iIndex with no change. Using an int16 solves the problem.
Obviously, the increment is happening first, and 'wrapping' the variable from 255 --> 0 before the evaluation takes place, hence the endless loop. So, is there any way this be done with a int8?
Jack |
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19539
|
|
Posted: Thu Apr 20, 2017 2:07 pm |
|
|
Use a do loop instead.
This way the test is at the end of the loop, so you can count up to 255, and get 256 loops.
Code: |
iIndex=0;
do
{
fprintf(Console, "Index: %u\n\r", iIndex);
delay_ms(50);
} while (++iIndex != 0);
|
You'll get 0,1, etc. right up to 255.
It then increments and wraps to 256, which is zero again in 8bit.
Obviously you can also just use:
Code: |
for ( iIndex = 0 ; iIndex != 0 ; iIndex++ )
|
|
|
|
JAM2014
Joined: 24 Apr 2014 Posts: 138
|
|
Posted: Thu Apr 20, 2017 3:03 pm |
|
|
Hi,
Of course, the 'Do' loop solution worked fine. I should have thought of that.....
This code, however, doesn't work. It never starts!
Code: |
for ( iIndex = 0 ; iIndex != 0 ; ++iIndex )
{
fprintf(Console, "Index: %u\n\r", iIndex);
delay_ms(50);
}
|
Jack |
|
|
PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
|
Posted: Thu Apr 20, 2017 6:18 pm |
|
|
After the init, it next does the test. The test will fail, so the "for loop" ends
immediately with no execution of the body.
The test is "iIndex != 0" and it says "run the body if iIndex is not zero".
But iIndex is 0 (it's set by the init section) so the body will never run.
The key point is the test is run right after the init. |
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19539
|
|
Posted: Thu Apr 20, 2017 10:39 pm |
|
|
Yes.
Unfortunately, since the test is at the start of the loop you have to get sneaky, and add another test inside the loop. It gets 'messy'. That's the key point about the do, where the test is after the pass.
For for, the trick you use is to count 'back' one, on the first pass. Unfortunately it means you get 1,1,2,3,4,5... |
|
|
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
Powered by phpBB © 2001, 2005 phpBB Group
|