However, when currDigit is declared as a byte, the loop goes 3, 2, 1, 0, -1, -2,... until something breaks.
I realized subtracting one from a byte that equals zero (or any other unsigned number) makes the value overflow:
(byte)0 - 1 = B11111111, which is still greater than zero. So the for loop continues forever.
It doesn't really matter if currDigit is a byte or an int in my program, so it's not a big problem for me now.
But, for education's sake: what if currDigit HAD to be a byte or other unsigned number that counted down to zero? What would be a good conditional statement to have in the for loop?
In order to fully leverage the advantages of the solution suggested I would advise that you engage our team of experienced consultants who will, no doubt, conclude that you need more consultancy.
Having worked for a few very large corporations that occasionally hire "consultants" I wholeheartedly agree.
Because then, you don't have to think for yourself.
There is the added benefit that, when something goes horrible wrong, the consultants can be blamed.
The risk is that "consultants are evaluating the situation" is sometimes followed by "we are heeding the consultants' advice and conducting a round of layoffs".
ainbritain:
But, for education's sake: what if currDigit HAD to be a byte or other unsigned number that counted down to zero? What would be a good conditional statement to have in the for loop?
You could use 'short' which is the same size as a 'byte' but handles short numbers up to a range of 127 in the positive range:
// for processing "short" numbers up to the range of 127:
for(short currDigit=3; currDigit>=0; currDigit--)
{
//do stuff
}
And if it actually has to be a byte, you can do the processig until it rolls over.
If you substract 1 from a byte that is 0, the byte becomes 255.
// for processing "byte" numbers up to the range of 254:
for(byte currDigit=3; currDigit<=3; currDigit--)
{
//do stuff
}
And last but not least: You can tell the C-preprocessor, that a 'byte' shall not be a 'byte' but an 'int' when you are writing your loop:
As 'byte' is not an internal data type of the C language or the compiler, but it is only defined in the Arduino core files. You can define a 'byte' to be anything you want. Also an int.