zoukankan      html  css  js  c++  java
  • [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).

  • 相关阅读:
    npm 默认创建项目如何自动配置
    VueJS + TypeScript 入门第一课
    实现类数组转化成数组(DOM 操作获得的返回元素值是一个类数组)
    webpack4(4.41.2) 打包出现 TypeError this.getResolve is not a function
    vue-cli 4.0.5 配置环境变量样例
    关于H5页面在微信浏览器中音视频播放的问题
    ant-design-vue 快速避坑指南
    记elementUI一个大坑
    VUE自定义(有限)库存日历插件
    node转发请求 .csv格式文件下载 中文乱码问题 + 文件上传笔记
  • 原文地址:https://www.cnblogs.com/diegodu/p/4580292.html
Copyright © 2011-2022 走看看