do {…} while(false)

前端 未结 25 2452
小鲜肉
小鲜肉 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

    Many answerers gave the reason for do{(...)break;}while(false). I would like to complement the picture by yet another real-life example.

    In the following code I had to set enumerator operation based on the address pointed to by data pointer. Because a switch-case can be used only on scalar types first I did it inefficiently this way

    if (data == &array[o1])
        operation = O1;
    else if (data == &array[o2])
        operation = O2;
    else if (data == &array[on])
        operation = ON;
    
    Log("operation:",operation);
    

    But since Log() and the rest of code repeats for any chosen value of operation I was wandering how to skip the rest of comparisons when the address has been already discovered. And this is where do{(...)break;}while(false) comes in handy.

    do {
        if (data == &array[o1]) {
            operation = O1;
            break;
        }
        if (data == &array[o2]) {
            operation = O2;
            break;
        }
        if (data == &array[on]) {
            operation = ON;
            break;
        }
    } while (false);
    
    Log("operation:",operation);
    

    One may wonder why he couldn't do the same with break in an if statement, like:

    if (data == &array[o1])
    {
        operation = O1;
        break;
    }
    else if (...)
    

    break interacts solely with the closest enclosing loop or switch, whether it be a for, while or do .. while type, so unfortunately that won't work.

提交回复
热议问题