do {…} while(false)

前端 未结 25 2539
小鲜肉
小鲜肉 2020-11-28 03:29

I was looking at some code by an individual and noticed he seems to have a pattern in his functions:

 function()
{
 

        
25条回答
  •  佛祖请我去吃肉
    2020-11-28 04:00

    Some coders prefer to only have a single exit/return from their functions. The use of a dummy do { .... } while(false); allows you to "break out" of the dummy loop once you've finished and still have a single return.

    I'm a java coder, so my example would be something like

    import java.util.Arrays;
    import java.util.List;
    import java.util.Set;
    import java.util.stream.Collectors;
    import java.util.stream.Stream;
    
    public class p45
    {
        static List cakeNames = Arrays.asList("schwarzwald torte", "princess", "icecream");
        static Set forbidden = Stream.of(0, 2).collect(Collectors.toSet());
    
        public static  void main(String[] argv)
        {
            for (int i = 0; i < 4; i++)
            {
                System.out.println(String.format("cake(%d)=\"%s\"", i, describeCake(i)));
            }
        }
    
    
        static String describeCake(int typeOfCake)
        {
            String result = "unknown";
            do {
                // ensure type of cake is valid
                if (typeOfCake < 0 || typeOfCake >= cakeNames.size()) break;
    
                if (forbidden.contains(typeOfCake)) {
                    result = "not for you!!";
                    break;
                }
    
                result = cakeNames.get(typeOfCake);
            } while (false);
            return result;
        }
    }
    

提交回复
热议问题