Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating from MinValue to MaxValue with overflow

Tags:

c#

for-loop

I have a simple loop which should look like this

for (sbyte i = sbyte.MinValue; i <= sbyte.MaxValue; i++)
{
    Console.WriteLine(i);
}

unfortunately sbyte.MaxValue +1 = sbyte.MinValue so this never meets the ending condition. My workaround was using int from -128 to 127 but is there also a native sbyte approach?

like image 903
Toshi Avatar asked May 05 '17 08:05

Toshi


3 Answers

Not taking into consideration an obvious

output all except MaxValue, then output MaxValue

approach, I see one solution.
It works, but looks weird and throws OverflowException if checked :)

sbyte i = sbyte.MinValue;
do
{
    Console.WriteLine(i++);
} while (i != sbyte.MinValue);
like image 62
Yeldar Kurmangaliyev Avatar answered Sep 29 '22 12:09

Yeldar Kurmangaliyev


You can try this :

for (sbyte i = sbyte.MinValue; i <= sbyte.MaxValue; i++)
{
    Console.WriteLine(i);
    if(i==sbyte.MaxValue)
     break;
}
like image 22
Nishesh Pratap Singh Avatar answered Sep 29 '22 14:09

Nishesh Pratap Singh


You can use an int just for the condition and the sbyte inside.

int checkVal = sbyte.MinValue;
for (sbyte i = sbyte.MinValue; checkVal <= sbyte.MaxValue; i++, checkVal++)
{
    Console.WriteLine(i);
}
like image 20
Ofir Winegarten Avatar answered Sep 29 '22 13:09

Ofir Winegarten