Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 759
esote Avatar asked Sep 03 '16 00:09

esote


1 Answers

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.

like image 179
chris Avatar answered Sep 21 '22 15:09

chris