Search code examples
c++cllvm-clanggoto

What is an indirect goto statement?


In Clang API, there is a GotoStmt and an IndirectGotoStmt. There is very little explanation on the difference between these two kinds of goto statments. I know what a goto label; statement is. But what is an indirect goto statement? I want to know what that is in the context of C/C++ code, not necessarily just Clang. What does it mean syntactically to have an indirect goto statement? Can you provide a code example?

Edit: The following question is interesting.

Can you make a computed goto in C++


Solution

  • There is a GNU extension that allows taking an address of a label, storing it for later use, then goto that address at a later point. See https://gcc.gnu.org/onlinedocs/gcc/Labels-as-Values.html for details. Example:

        void *ptr;
    
        if(...)
            ptr = &&foo;
        else
            ptr = &&bar;
    
        /* ... */
        goto *ptr;
    
    foo:
        /* ... */
    
    bar:
        /* ... */
    

    Clang supports that too, as it aims at being compatible with GCC.

    The use of the above might be, for example, in implementing state machines.