Ahoura Ghotbi
Ahoura Ghotbi

Reputation: 2896

issue with switch inside a do while, control cannot fall through from one case label to another

I have the following code :

        do{

        Console.Write("Please Input a Value: ");
        userInput = Console.ReadLine();

        v = userInput.ToString().Substring(0, 1);
        amount = Convert.ToInt32(userInput.ToString().Substring(1, 1));

        switch(v)
        {
            case "a": mother.incr1(amount);
            case "s": mother.incr10(amount);
            case "d": mother.incr100(amount);
            case "f": mother.incr1000(amount);
            case "=": Console.WriteLine("The total amount is: {0} \n", mother.current);
            case "r": mother.current = 0;
        }

        }while(mother.overflow() != true);

when I added the do while, it returned an error "control cannot fall through from one case label #caselabelname# to another" on all the case lines

Upvotes: 0

Views: 668

Answers (3)

Hans Passant
Hans Passant

Reputation: 941635

C# inherited the switch statement from the C language. Which has case statement fall through, an incredibly fertile source of hard to diagnose bugs. In your code, fall through will always leave mother.current set to 0.

The C# language requires you to terminate a case statement explicitly to avoid this trap. You must either use break to let code resume at the statement following the switch statement. Or use goto case to direct it to resume execution into another case statement. The break keyword is clearly the appropriate choice here.

Upvotes: 1

Joe Mancuso
Joe Mancuso

Reputation: 2129

Since v can only be a single character at a time, there is no reason to allow the case to fall through. You should put a break at the end of each case.

Upvotes: 1

Mike Hanrahan
Mike Hanrahan

Reputation: 1192

You need to put a "break;" between each statement

  switch(v) 
    { 
        case "a": 
                mother.incr1(amount); 
                break;
        case "s": 
               mother.incr10(amount); 
               break;
        etc.etc. 
    } 

Upvotes: 1

Related Questions