简体   繁体   中英

function definition without prototype

when function definition is below, and there is no function prototype.

int main(void)
{
        func();
        void (*pFunc)(void) = func;
}

void func(void)
{
}
main.c:3:2: warning: implicit declaration of function 'func' is invalid in C99 [-Wimplicit-function-declaration]
        func();
        ^
main.c:4:9: error: incompatible function pointer types initializing 'void (*)(void)' with an expression of type 'int ()' [-Werror,-Wincompatible-function-pointer-types]
        void (*pFunc)(void) = func;
               ^              ~~~~
main.c:4:9: warning: unused variable 'pFunc' [-Wunused-variable]
main.c:7:6: error: conflicting types for 'func'
void func(void)
     ^
main.c:3:2: note: previous implicit declaration is here
        func();
        ^
2 warnings and 2 errors generated.

I can call a function without function prototpype(ignoring implicit function declaration), but why I can't get the adress of the function?

  • warning: implicit declaration of function 'func' is invalid in C99

    What this actually says is: your code is not valid C. There is no telling what it will do and no guarantees.

  • func(); This invokes a non-standard gcc extension known as implicit function declarations/implicit int, which was once part of the C language a very long time ago. It means that it will take a guess of the types - always assuming that this is a function returning int and taking any parameter - same as if you would have typed int func();. Which is plain wrong and will not work.

  • error: incompatible function pointer types initializing 'void (*)(void)' with an expression of type 'int ()'

    Since we got the function declaration completely wrong above, we get this compiler error. The function pointer is not compatible with the type declared.

  • error: conflicting types for 'func'

    This error happens when we reach the function definition void func (void) , which collides with the previous definition int func (); .


Solution:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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