简体   繁体   English

如何返回main而不是函数调用它?

[英]How to return to main and not the function calling it?

I have a function() which calls anotherFunction() . 我有一个function() ,它调用anotherFunction() Inside anotherFunction() , there is an if statement which, when satisfied returns back to main() and not to function() . anotherFunction()内部,有一个if语句,当满足时,该语句将返回main()而不是function() How do you do this? 你怎么做到这一点?

You can't do like that in "standard" C. You can achieve it with setjmp and longjmp but it's strongly discouraged. 您无法在“标准” C语言中做到这一点。您可以使用setjmplongjmp来实现,但强烈建议不要这样做。

Why don't just return a value from anotherFuntion() and return based on that value? 为什么不只是从anotherFuntion()返回一个值并基于该值返回呢? Something like this 像这样

int anotherFunction()
{
    // ...
    if (some_condition)
        return 1; // return to main
    else
        return 0; // continue executing function()
}

void function()
{
    // ...
    int r = anotherFuntion();
    if (r)
        return;
    // ...
}

You can return _Bool or return through a pointer if the function has already been used to return something else 您可以返回_Bool或通过指针返回(如果该函数已用于返回其他内容)

You can bypass the normal return sequence in C with the setjmp and longjmp functions. 您可以使用setjmp和longjmp函数绕过C中的正常返回序列。

They have an example at Wikipedia: 他们在Wikipedia上有一个例子:

#include <stdio.h>
#include <setjmp.h>

static jmp_buf buf;

void second(void) {
    printf("second\n");         // prints
    longjmp(buf,1);             // jumps back to where setjmp was called - making setjmp now return 1
}

void first(void) {
    second();
    printf("first\n");          // does not print
}

int main() {   
    if ( ! setjmp(buf) ) {
        first();                // when executed, setjmp returns 0
    } else {                    // when longjmp jumps back, setjmp returns 1
        printf("main\n");       // prints
    }

    return 0;
}

You can't easily do that in C. Your best bet is to return a status code from anotherFunction() and deal with that appropriately in function() . 在C语言中,您不容易做到这一点。最好的选择是从anotherFunction()返回状态代码,并在function()中进行适当处理。

(In C++ you can effectively achieve what you want using exceptions). (在C ++中,您可以使用异常有效地实现所需的功能)。

Most languages have exceptions which enable this sort of flow control. 大多数语言都具有启用此类流控制的异常 C doesn't, but it does have the setjmp / longjmp library functions which do this. C没有,但是它确实具有setjmp / longjmp库函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM