Anonymous Anonymous - 3 months ago 17
C++ Question

C++ Goto variable

Is there a way to call a goto statement using a variable in the place of a label name?

I'm looking for something similar to this (this doesn't work for me):

// std::string or some other type that could represent a label
void callVariable(std::string name){
goto name;
}

int main(){
first:
std::cout << "Hi";
callVariable(first);

return 0;
}


I am not actually using this, I am more interested in learning.

Answer

Yes and no. There's no such standard language feature, but it is a compiler extension in at least GCC:

int main() {
    void* label;

    first:
    std::cout << "Hi";
    label = &&first;
    goto *label;
}

That said, I'd have to think hard for a use case where this is better than any standard alternatives.