Using Goto function across different functions

前端 未结 4 2085
心在旅途
心在旅途 2020-12-18 20:58

How can I use goto function across different functions .For ex ,

    main()
    {
      ....
      REACH:
      ......
    }

    void function()
    {
             


        
相关标签:
4条回答
  • 2020-12-18 21:12

    You can't. Think of this. There is a function A which is recursively calling another function B which in turn is calling A. Now, suppose that you put a goto statement from A to B. The question now becomes which instance of A do you want to go to which is undefined. Also, if no previous instance of A is defined, you have a bigger problem of no initialized variables in the function that are present before the label.

    #include "bits/stdc++.h"
    int i=0;
    A(){
    run:
        B();
    }
    B(){
    if(i==10)
        goto run;
    i++;
    A();
    }
    
    0 讨论(0)
  • 2020-12-18 21:17

    You can't in Standard C; labels are local to a single function.

    The nearest standard equivalent is the setjmp() and longjmp() pair of functions.

    GCC has extensions to support labels more generally.

    0 讨论(0)
  • 2020-12-18 21:24

    You can't in Standard C++. From $6.6.4/1 of the C++ Language Standard

    The goto statement unconditionally transfers control to the statement labeled by the identifier. The identifier shall be a label (6.1) located in the current function.

    ...or in Standard C. From $6.8.6.1/1 of the C Language Standard

    The identifier in a goto statement shall name a label located somewhere in the enclosing function. A goto statement shall not jump from outside the scope of an identifier having a variably modified type to inside the scope of that identifier.

    0 讨论(0)
  • 2020-12-18 21:29

    For gcc:

    #include <iostream>
    
    void func(void* target){
        std::cout << "func" <<std::endl;
        goto *target;
    }
    
    
    int main() {
        void* target;
        auto flag = true;
    l:
        std::cout << "label" <<std::endl;
        target = &&l;
        if (flag) {
            flag = false;
            func(target);
      }
    }
    

    Note that this can be an undefined behavior

    0 讨论(0)
提交回复
热议问题