• [C/CPP系列知识] 在C中使用没有声明的函数时将发生什么 What happens when a function is called before its declaration in C


    http://www.geeksforgeeks.org/g-fact-95/

    1 在C语言中,如果函数在声明之前被调用,那么编译器假设函数的返回值的类型为INT型,

    所以下面的code将无法通过编译:

    #include <stdio.h>
    int main(void)
    {
        // Note that fun() is not declared 
        printf("%d
    ", fun());
        return 0;
    }
     
    char fun()
    {
       return 'G';
    }

    错误:其实就是fun函数定义了两遍,冲突了

    test1.c:9:6: error: conflicting types for 'fun'
     char fun()
          ^
    test1.c:5:20: note: previous implicit declaration of 'fun' was here
         printf("%d
    ", fun());
                        ^

    将返回值改成int行可以编译并运行:

    #include <stdio.h>
    int main(void)
    {
        printf("%d
    ", fun());
        return 0;
    }
     
    int fun()
    {
       return 10;
    }

    2 在C语言中,如果函数在声明之前被调用,如果对函数的参数做检测?

    compiler assumes nothing about parameters. Therefore, the compiler will not be able to perform compile-time checking of argument types and arity when the function is applied to some arguments. This can cause problems.

    编译器对参数不做任何假设,所以无法做类型检查。 下面code就会有问题,输出是garbage

    #include <stdio.h>
     
    int main (void)
    {
        printf("%d", sum(10, 5));
        return 0;
    }
    int sum (int b, int c, int a)
    {
        return (a+b+c);
    }

    输出结果:

    diego@ubuntu:~/myProg/geeks4geeks/cpp$ ./a.out 
    1954607895
    diego@ubuntu:~/myProg/geeks4geeks/cpp$ ./a.out 
    1943297623
    diego@ubuntu:~/myProg/geeks4geeks/cpp$ ./a.out 
    -16827881
    diego@ubuntu:~/myProg/geeks4geeks/cpp$ ./a.out 
    67047927
    diego@ubuntu:~/myProg/geeks4geeks/cpp$ ./a.out 
    -354871129
    diego@ubuntu:~/myProg/geeks4geeks/cpp$ ./a.out 
    -562983177
    diego@ubuntu:~/myProg/geeks4geeks/cpp$ ./a.out 
    33844135
    diego@ubuntu:~/myProg/geeks4geeks/cpp$

    所以It is always recommended to declare a function before its use so that we don’t see any surprises when the program is run (See this for more details).

  • 相关阅读:
    MySQL 查询树结构、循环查询、查看函数、视图、存储过程
    SpringBoot 部署:外置依赖包
    springboot集成docker实现自动化构建镜像说明
    Chrome谷歌浏览器常用快捷键、开发技巧
    Windows常用CMD命令
    Git 版本管理,与 SVN区别对比
    TensorFlow重新导入restore报错: OP_REQUIRES failed at save_restore_v2_ops.cc:184 : Not found: Key Variable not found in checkpoint
    MySQL字符集设置
    Hive 时间操作
    深度思考:如何规划你的职业生涯
  • 原文地址:https://www.cnblogs.com/diegodu/p/4580292.html
Copyright © 2020-2023  润新知