Search code examples
c++goto

Using goto for optimization


Hi i was wandering if using goto is good practice for optimization. i know it's a barbarian thing to do but, seriously.

for instance write this:

switch(command[0].cmd)
{
    case 0: // turn off
        s::s_off();
        S_time = command[0].length;
    break;
    case 1: // turn on
        s::s_on();
        S_time = command[0].length;
    break;
    case 4: // nop

    break;
}

like this:

switch(command[0].cmd)
{
    case 0: // turn off
        s::s_off();
        goto a;
    break;
    case 1: // turn on
        s::s_on();
        goto a;
    break;
    case 4: // nop
        goto b;
    break;
}

a:
S_time = command[0].length;
b:

Solution

  • It is not recommended to use goto frequently. But it is not "evil" and in many cases is much easier to put 1 goto instead of more complex logic only to avoid the "evil". And in your example single goto is enough:

    switch(command[0].cmd)
    {
        case 0: // turn off
            s::s_off();
            break;
    
        case 1: // turn on
            s::s_on();
            break;
    
        case 4: // nop
            goto b; // break after goto is useless
    }
    
    S_time = command[0].length;
    b: