2016-10-01 3 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 : // 유래 .com/questions/3674200/what-does-a-typedef-with-parenthesis-like-typedef-int-fvoid-mean-is-it-a –

답변

2

world = &f;은 모두 인수로 전달할 때 f&f 사이에 차이가 없기 때문에 작동합니다.

C99 사양 (섹션 6.7.5.3.8)을 참조하십시오.

"함수를 반환하는 형식"으로 매개 변수 선언은 6.3.2.1에서와 같이 "함수 반환 형식의 포인터"로 조정해야합니다.

1

함수 f 유형 int (void *_)이다. f이 표현식에서 사용될 때마다 암시 적으로 int(*) (void *_) 유형의 포인터로 변환됩니다.

어떤 것을 사용해야합니까?

그래서, 모든 실제적인 목적을 위해, 함수 f의 이름과 동일한 기능 &f에 대한 포인터는 교환 할 수있다. 또한 컴파일러 또는 C 버전에 따라 다릅니다 않습니다 "Why do all these function pointer definitions all work? "

를 보라?

컴파일러 또는 C 버전에 의존하지 않습니다.