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).

  • 相关阅读:
    如何高效查看 Docker 日志
    linux:有效使用docker logs查看日志
    FFmpeg命令行工具学习(一):查看媒体文件头信息工具ffprobe
    性能调优
    【禅道】Windows本地安装禅道2.0.9
    Handle
    Operate the elements
    Web功能测试常用方法
    Drop down box selection(Select)
    Iframe
  • 原文地址:https://www.cnblogs.com/diegodu/p/4580292.html
Copyright © 2011-2022 走看看