简体   繁体   中英

scope of function declaration in c

i have read in various places that functions which are declared in main() cannot be called outside main. But in below program fun3() is declared inside main() and called outside main() in other functions, and IT WORKS, giving output 64.here's link http://code.geeksforgeeks.org/7EZZxQ .however,if i change fun3() return type int to void ,it fails to compile,whats reason for this behaviour?

#include <stdio.h>
 #include <stdlib.h>


int main()
{
    void fun1(int);
    void fun2(int);
    int fun3(int); 

    int num = 5;
    fun1(num);
    fun2(num);
}

void fun1(int no)
{
    no++;
    fun3(no);
}

void fun2(int no)
{
    no--;
    fun3(no);

}

int fun3(int n)
{
    printf("%d",n);
}

there is fail in compilation when declaration of fun3() is changed.

 #include <stdio.h>
 #include <stdlib.h>


int main()
{
    void fun1(int);
    void fun2(int);
    void fun3(int);     //fun3 return type changed to void error in compilation

    int num = 5;
    fun1(num);
    fun2(num);
}

void fun1(int no)
{
    no++;
    fun3(no);
}

void fun2(int no)
{
    no--;
    fun3(no);

}

void fun3(int n)   //fun3 return type changed to void error in compilation
{
    printf("%d",n);
}

Prior to the C99 standard, if the compiler saw a function call without a function declaration in the same scope, it assumed that the function returned int .

Neither fun1 nor fun2 declare fun3 before they call it, nor do they see the declaration in main ; the declaration of fun3 in main is limited to the body of main . Under C89 and earlier, the compiler will assume that the call to fun3 returns an int . In the first example, the definition of fun3 returns an int so the code will compile under a C89 compiler. In the second example, the definition of fun3 returns void , which doesn't match the assumed int type, so the code fails to compile.

Under C99 and later standards, neither snippet will compile; the compiler no longer assumes an implicit int declaration for a function call. All functions must be explicitly declared or defined before they are called.

声明仅在声明的范围内有效。 但是 ,在较早的C标准中,如果在调用时不存在函数声明,则允许编译器猜测函数声明,这可能是您所遇到的情况:编译器看到了呼叫fun3fun1fun2fun3 ,并推导出(猜测)根据您的通话传递参数的参数类型。

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