I am having trouble with the following code it seems that the break statement is good but I could not be seeing something.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Switch
{
class swtich
{
static void Main(string[] args)
{
string input; int num;
Console.WriteLine("Enter a number from 0-6: ");
input = Console.ReadLine();
num = int.Parse(input);
switch (num)
{
case 0:
Console.WriteLine("Sunday");
break;
case 1:
Console.WriteLine("Monday");
break;
case 2:
Console.WriteLine("Tuesday");
break;
case 3:
Console.WriteLine("Wednesday");
break;
case 4:
Console.WriteLine("Thursday");
break;
case 5:
Console.WriteLine("Friday");
break;
case 6:
Console.WriteLine("Saturday");
break;
default:
Console.WriteLine("Invalid input");
}
}
}
}
this is the error I am getting Control cannot fall through from one case label ('default:') to another
Put a break;
after your default:
case.
...
case 6:
Console.WriteLine("Saturday");
break;
default:
Console.WriteLine("Invalid input");
break;
}
The default
case isn't required to be at the end, so you have to include a break
just like everywhere else to avoid this warning.
Unlike the switch
statements in C, C++ or Java, C# does not allow case statements to fall through, This includes the default
case statement. You must add break
after your default
case.
default:
Console.WriteLine("Invalid Input");
break; // this is required
As @AlexeiLevenkov pointed out, break
isn't necessarily required, however, some kind of statement that prevents reaching the end of the construct is required, such as return
, break
or goto case
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With