2016-10-01 155 views
6

讓我們來看看下面的代碼:C函數名稱或函數指針?

#include <stdio.h> 

typedef int (*callback) (void *arg); 
callback world = NULL; 

int f(void *_) { 
    printf("World!"); 
    return 0; 
} 

int main() { 
    printf("Hello, "); 
    // world = f; 
    world = &f; // both works 
    if (world != NULL) { 
     world(NULL); 
    } 
} 

當設置world變量,既 world = f;world = &f;作品。

應該使用哪一個?它依賴於編譯器還是C版本?

% gcc -v 
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1 
Apple LLVM version 8.0.0 (clang-800.0.38) 
Target: x86_64-apple-darwin15.6.0 
Thread model: posix 
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin 
+4

http://stackoverflow.com/questions/6293403/in-c-what-is-the-difference-between-function-and-function-when-passed-as-a – Pavel

+0

http:// stackoverflow .COM /問題/ 3674200 /什麼,做-A-的typedef與 - 括號樣的typedef INT-fvoid均值 - 是 - 它-A –

回答

2

world = f;world = &f;都可以使用,因爲在將它作爲參數傳遞時,f&f之間沒有區別。

參見C99規範(第6.7.5.3.8節)。

參數聲明爲「函數返回類型」應調整爲「指向函數返回類型的指針」,如6.3.2.1所示。

1

你的功能fint (void *_)類型。每當在表達式中使用f時,它都會隱式轉換爲指向自身的指針,該指針的類型爲int(*) (void *_)

我應該使用哪一個?

因此,出於所有實際目的,函數f的名稱和指向相同函數&f的指針是可互換的。也看看"Why do all these function pointer definitions all work? "

它取決於編譯器或C版本嗎?

不依賴於任何的編譯器或C版本。