2014-12-05 68 views
-1

我有一個function(),它調用anotherFunction()。 在anotherFunction()裏面,有一條if語句,當滿足時返回main()而不是function()。你怎麼做到這一點?謝謝。如何返回主,而不是調用它的函數

+0

@mafso通過返回一個指針:啊,你說得對。標準中提到「初始調用main()'」暗示可能有其他的。 – 2014-12-05 17:03:30

回答

2

您可以用setjmp和longjmp函數繞過C中的正常返回序列。

他們有一個例子,在維基百科:

#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; 
} 
1

你不能輕易做,在C.你最好的賭注是從anotherFunction()返回狀態代碼和function()處理該適當。

(在C++中,你可以使用異常有效地實現你想要的)。

+0

這是不正確的。標準的setjmp和longjmp提供了這個功能。 – b4hand 2014-12-05 17:06:26

+1

我想這很容易*。我不喜歡存儲緩衝區。我真的不會推薦它,並堅持使用返回碼的建議。 – Bathsheba 2014-12-05 17:07:33

1

大多數語言都有例外這使得這種類型的流量控制。 C沒有,但它確實具有執行此操作的庫函數setjmp/longjmp

5

在「標準」C中,你不能那樣做。你可以用setjmplongjmp來實現,但是強烈建議你不要這麼做。

爲什麼不只是從anotherFuntion()返回一個值並根據該值返回?事情是這樣的

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

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

您可以返回_Bool或者如果該功能已經被用來返回別的東西

+0

@Bathsheba它可能在某些情況下有用,但在這種情況下不會有用,因爲有更簡單和更安全的解決方案 – 2014-12-05 16:56:45

+2

setjmp和longjmp都是標準C,因爲您甚至可以引用它們。 – b4hand 2014-12-05 16:59:29

相關問題